Python Variable Names
Learn the rules for naming variables in Python, including starting with a letter or underscore, avoiding starting with a number, and ensuring names are case-sensitive and do not conflict with Python keywords.
Variable Names in Python
In Python, a variable can have a short name (like x
and y
) or a more descriptive name (like age
, carname
, or total_volume
). Here are the rules for naming variables in Python:
- A variable name must start with a letter or the underscore character (_).
- A variable name cannot start with a number.
- A variable name can only contain alphanumeric characters and underscores (A-z, 0-9, and _).
- Variable names are case-sensitive (e.g.,
age
,Age
, andAGE
are three different variables). - A variable name cannot be any of the Python keywords.
Example
Legal Variable Names
myvar = "Alice"
my_var = "Bob"
_my_var = "Charlie"
myVar = "David"
MYVAR = "Eve"
myvar2 = "Frank"
print(myvar)
print(my_var)
print(_my_var)
print(myVar)
print(MYVAR)
print(myvar2)
Output
Alice
Bob
Charlie
David
Eve
Frank
Example (with Syntax Error)
Illegal Variable Names
2myvar = "Alice"
my-var = "Bob"
my var = "Charlie"
Error Output:
Traceback (most recent call last):
File "/usr/lib/python3.8/py_compile.py", line 144, in compile
code = loader.source_to_code source_bytes, dfile or file,
File "", line 846, in source_to_code
File "", line 219, in _call_with_frames_removed
File "./prog.py", line 1
2myvar = "Alice"
^
SyntaxError: invalid syntax
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python3.8/py_compile.py", line 150, in compile
raise py_exc
py_compile.PyCompileError: File "./prog.py", line 1
2myvar = "Alice"
^
SyntaxError: invalid syntax
Remember that variable names are case-sensitive.
Multi-Word Variable Names
Variable names with more than one word can be difficult to read. There are several techniques to make them more readable:
Camel Case
In Camel Case, each word, except the first, starts with a capital letter:
Example
myVariableName = "Alice"
Pascal Case
In Pascal Case, each word starts with a capital letter:
Example
MyVariableName = "Bob"
Snake Case
In Snake Case, each word is separated by an underscore:
Example
my_variable_name = "Charlie"