BasicsChapter 6 of 114
Variable Names
What Python allows, what it forbids, and what other people expect.
The rules
A name must start with a letter or an underscore, contain only letters, digits and underscores after that, and avoid the words Python has reserved for itself.
user_name = "Ada"
_private = True
count2 = 7
print(user_name, _private, count2)Output
Ada True 7
These are all errors: 2count starts with a digit, user-name contains a minus sign, and class is reserved.
Case matters
total, Total and TOTAL are three separate names:
value = 1
Value = 2
VALUE = 3
print(value, Value, VALUE)Output
1 2 3
Relying on that is a good way to confuse everyone, including yourself.
Reserved words
Thirty-five words belong to the language and cannot be used as names. You do not need to memorise them — your editor colours them, and Python can list them:
import keyword
print(len(keyword.kwlist))
print(keyword.kwlist[:6])Output
35 ['False', 'None', 'True', 'and', 'as', 'assert']
The convention: snake_case
Python code overwhelmingly uses lowercase words joined by underscores:
first_name = "Grace"
items_in_cart = 3
is_logged_in = True
print(first_name, items_in_cart, is_logged_in)Output
Grace 3 True
The other conventions you will meet:
| Style | Used for | Example |
|---|---|---|
snake_case | variables, functions | total_price |
CapWords | classes | ShoppingCart |
SCREAMING_SNAKE | constants | MAX_RETRIES |
_leading_underscore | internal, hands off | _cache |
Names are documentation
A name is read far more often than it is written. d saves four keystrokes once and costs a puzzled reader every time:
days_until_renewal = 14
print(f"Renews in {days_until_renewal} days")Output
Renews in 14 days
Test yourself
2 questionsWhich of these is a legal variable name?
Show the answer
_count2 — A name starts with a letter or underscore, holds only letters, digits and underscores, and is not a reserved word.
Why avoid naming a variable list?
Show the answer
It hides the builtin list for the rest of that scope — It is legal and that is the problem: the real function is gone and the error appears much later.
Multiple Assignment
Assign several names at once, unpack a sequence, and swap without a temporary.