Variable Names
Names can be as short as x or y, or more descriptive, such as age, carname, or total_volume.
Python sets a few rules for them. The first character has to be a letter or an underscore, never a number. After that, only letters, numbers, and underscores are allowed (A-Z, a-z, 0-9, and _). Names are case-sensitive, and no Python keyword can be used as a name.
Legal variable names
Prompt
Demonstrate six legal variable names in Python: myvar, my_var, _my_var, myVar, MYVAR, and myvar2, all assigned the value "John". Print one to verify.
Output: complete Python program
main.py
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
print(myvar)
print(my_var)
print(_my_var)
print(myVar)
print(MYVAR)
print(myvar2)
Illegal variable names
Prompt
Demonstrate three illegal variable names in Python: 2myvar, my-var, and my var. This code will produce errors.
Output: complete Python program
main.py
2myvar = "John"
my-var = "John"
my var = "John"
Multi-Word Variable Names
A name made of several words can be hard to read. A few common techniques help with that.
Camel Case
The first word stays lowercase and every word after it begins with a capital letter:
main.py
myVariableName = "John"
Pascal Case
All the words begin with a capital letter:
main.py
MyVariableName = "John"
Snake Case
An underscore sits between each pair of words:
main.py
my_variable_name = "John"