Understanding Python Variables
Avariableis 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 anobject holderthat 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 namedCoffeeCupandcoffeecupare 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 theprintfunction is. You have this function on your Raspbian system, but before you can use it, you need toimportthe function into Python. (You’ll learn more about importing a function in Hour 13, “Working with Modules.”) The function’s name iskeyword.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 commandimport keywordbrings thekeywordfunctions into the Python interpreter so they can be used. Then the statementprint(keyword.kwlist)uses thekeyword.kwlistandprintfunctions 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 mustnot使用一个数字。第一个字符的变量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.