Understanding Python Variables
A variable is a name that stores a value for later use in a script. A variable is like a coffee cup. A coffee cup typically holds coffee, of course! But a coffee cup can also hold tea, water, milk, rocks, gravel, sand...you get the picture. Think of a variable as a “holder of objects” that you can look at and use in your Python scripts.
When you name your coffee cup...err, variable...you need to be aware that Python variable names are case sensitive. For example, the variables named CoffeeCup and coffeecup are two different variables. There are other rules associated with creating Python variable names:
- You cannot use a Python keyword as a variable name.
- The first character of a variable name cannot be a number.
- There are no spaces allowed in a variable name.
Python Keywords
The list of Python keywords changes every so often. Therefore, it is a good idea to take a look at the current list of keywords before you start creating variable names. To look at the keywords, you need to use a function that is part of the standard library. However, this function is not built -in, like the print function is built -in. You have this function on your Raspbian system, but before you can use it, you need to import the function into Python. The function’s name is keyword. Listing 4.12 shows you how to import into Python and determine keywords.
LISTING 4.12 Determining Python Keywords
>>> import keyword >>> print (keyword.kwlist) ['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'] >>>
In Listing 4.12, the command import keyword brings the keyword function into the Python interpreter so it can be used. Then the statement print (keyword.kwlist) uses the keyword and print functions to display the current list of Python keywords. These keywords cannot be used as Python variable names.
Creating Python Variable Names
For the first character in your Python variable name, you must not use a number. The first character in the variable name can be any of the following:
- A letter a through z
- A letter A through Z
- The underscore character (_)
After the first character in a variable name, the other characters can be any of the following:
- The numbers 0 through 9
- The letters a through z
- The letters A through Z
- The underscore character (_)
After you determine a name for a variable, you still cannot use it. A variable must have a value assigned to it before it can be used in a Python script.