Variable Names and KeywordsΒΆ
- Variable names can be arbitrarily long.
- They can contain both letters and digits, but they have to begin with a letter or an underscore.
- Although it is legal to use uppercase letters, by convention we don’t.
- Case matters.
Bruceandbruceare different variables. - The underscore character (
_) can appear in a name (often used in names with multiple words, such asmy_nameorprice_of_tea_in_china). - A safe rule for beginners is to start all names with a letter.
If you give a variable an illegal name, you get a syntax error:
(wrongassignment)
76trombonesis illegal because it does not begin with a letter.more$is illegal because it contains an illegal character, the dollar sign.- But what’s wrong with
class?classis one of the Python keywords.
Keywords define the language’s syntax rules and structure, and they cannot be used as variable names.
Python has thirty-something keywords:
| and | as | assert | break | class | continue |
| def | del | elif | else | except | exec |
| finally | for | from | global | if | import |
| in | is | lambda | nonlocal | not | or |
| pass | raise | return | try | while | with |
| yield | True | False | None |
Programmers generally choose names for their variables that are meaningful to the human readers of the program to remember what the variable is used for.