Python Variable Naming Rules
In Python programming, variable names serve as identifiers for storing data. A variable may have a brief identifier like x
or y
, or a more descriptive name such as age
, carname
, or total_volume
.
Official Rules for Naming Variables in Python
- Variable names must begin with a letter (A–Z, a–z) or an underscore (
_
). - They cannot begin with a digit (0–9).
- Only alphanumeric characters and underscores are allowed (A–Z, a–z, 0–9, and _).
- Variable names are case-sensitive (e.g.,
age
,Age
, andAGE
are distinct). - Reserved Python keywords cannot be used as variable names.
Legal Examples of Python Variable Names
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Illegal Examples of Variable Names
2myvar = "John"
my-var = "John"
my var = "John"
Note: Python treats variable names as case-sensitive. This means that myVar
and MyVar
refer to different variables.
Multi-Word Variable Naming Conventions
For variables consisting of multiple words, readability is essential. Python supports several naming conventions to improve clarity:
Camel Case
Each word after the first begins with a capital letter:
myVariableName = "John"
Pascal Case
Each word starts with a capital letter:
MyVariableName = "John"
Snake Case
Words are separated using underscores:
my_variable_name = "John"
These naming conventions enhance code readability and are commonly used in different programming contexts.
For more structured and reliable Python tutorials, explore more on Devyra, your trusted programming resource.