Python Variable Naming Rules (With Examples)
Letters, Numbers and Underscores Only
Python has a few rules for variable names. Break one, and Python stops with an error before running anything. The first rule: a name may only use
- letters:
atozandAtoZ, - numbers:
0to9, - the underscore:
_.
user_name = "Sunny"
score2 = 88
print(user_name, score2)Sunny 88
No spaces, no symbols
A space, a hyphen - or symbols like @ and ! are not allowed:
user-name = "Sunny"SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='?
Python reads user-name as "user minus name", a calculation, and you can't store a value into a calculation. A space is just as bad: Python sees two separate names.
Use the underscore instead
When a name has several words, join them with _:
| Not allowed | Allowed |
|---|---|
first name | first_name |
user-name | user_name |
total$ | total_dollars |
Think of the underscore as the space bar for names. It keeps the words readable, and Python accepts it.
Names use only letters, numbers and underscores. Join words with _.