Tuesday 24 May 2011

Naming Conventions and More

Okay, so you've made it this far. Great work! Following the last couple of lessons, we will be going a bit more in-depth into the Python Naming Rules and Conventions, Keywords, Constants,  Variables and Comments.



To start off, we will look at the rules for naming your variables.
  • All names must start with a letter
  • They may contain: letters, numbers, and the underscore character ( _ )
  • The names are case sensitive. count is different from Count
  • There are certain keywords that cannot be used (seen later on)
There are also some conventions that are recommended:
  • Using lowercase letters for variable names
  • Using UPPERCASE letters for constants (seen later on)
  • The names should be short enough to remember and must be self descriptive
If you keep these things in mind, you will have a cleaner looking program, as well as one that can be easily read by other programmers.

As discussed above, there are certain keywords that cannot be used for variable names. They are as follows:

False None True and
as assert break class
continue def del elif
else except finally for
from global if import
in is lambda nonlocal
not or pass raise
return try while with
yield


As long as you stay away from these variable names you will have no problems. The next thing to cover is Variables and Constants.

These are defined as:

Variable:
  • adjective. able or liable to change 
  • noun. a name given to a memory location designed to store a data value (Comp.Sci.)
  • Called ‘variable’ as the value stored in it is likely to change during program execution
Constant:
  • noun. a quantity that has a fixed value throughout a set of calculations
  • Called ‘constant’ as once set, the value stored does not/cannot change during program execution
When using either of these, you have to take into account what the variable will be used to store, and whether or not you will need to change the value of it later on.

Comments are a great way to describe what each part of code is doing in your program. It's beneficial to both you and anyone else who reads your code. To add comments to your code its as simple as adding the hash sign. The comment will span the entire line, when writing longer comments, it is best to split it amongst multiple lines, each starting with the hash sign.


*NOTE* When using the print function, you must use quotations when outputting a string directly. If you are outputting a variable, they will not be needed (eg. print(myVariable))

When running your program, the comments will be ignored, they are only there for your benefit and the benefit of those who read the code.

That's it for this lesson. Play around with the comments and variables and see how you go. If you have any trouble, go back through the lessons, or post a comment, I'm happy to answer any questions you may have!

Continue on to: Exercises Part 1

-Nathan (everythingPython)

No comments:

Post a Comment