Python Variable Names
Python has clear rules for which variable names are legal and widely followed conventions for which names are readable.
The rules
A valid variable name must start with a letter or an underscore, and the rest of the name may contain letters, digits, and underscores. Names cannot begin with a digit, cannot contain spaces or punctuation such as hyphens, and are case sensitive, so age, Age, and AGE are three distinct variables.
- Must begin with a letter (a-z, A-Z) or an underscore ( _ ).
- May contain only letters, digits (0-9), and underscores after the first character.
- Cannot be one of Python's reserved keywords, such as if, for, class, or True.
- Are case sensitive: total and Total refer to different variables.
Legal and illegal names
# Valid
user_name = "Sam"
_private = 10
level2 = 99
# Invalid (each line would raise a SyntaxError)
# 2level = 99
# user-name = "Sam"
# class = "A"Naming styles
Because you often need multi-word names, developers rely on consistent naming styles to keep code readable. The Python community strongly favours snake_case for ordinary variables, where words are lowercase and joined by underscores.
Choosing a descriptive name is just as important as following the style. A name like days_remaining tells a reader far more than a bare d, and the small extra typing pays off every time the code is read again.
Readable names in practice
first_name = "Grace"
last_name = "Hopper"
MAX_LOGIN_ATTEMPTS = 3
full_name = first_name + " " + last_name
print(full_name)