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 also can hold tea, water, milk, rocks, gravel, sand...you get the picture. Think of a variable as an object holder 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. Other rules are associated with creating Python variable names, as well:
- You cannot use a Python keyword as a variable name.
- The first character of a variable name cannot be a number.
- No spaces are allowed in a variable name.
Python Keywords
The Python keywords list changes every so often. Therefore, it is a good idea to take a look at the current keywords list before you start creating variable names. To look at the keywords, you need to use a standard library function. However, this function is not built in, like the print function is. You have this function on your Raspbian system, but before you can use it, you need to import the function into Python. (You’ll learn more about importing a function in Hour 13, “Working with Modules.”) The function’s name is keyword.kwlist. 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 functions into the Python interpreter so they can be used. Then the statement print(keyword.kwlist) uses the keyword.kwlist 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–z
- A letter A–Z
- The underscore character (_)
After the first character in a variable name, the other characters can be any of the following:
- The numbers 0–9
- The letters a–z
- The letters A–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.