What Are Python Variable Names?
In Python, variable names are identifiers used to label data stored in memory so you can reference and manipulate that data throughout a program. A variable name must follow specific rules and conventions so that the Python interpreter accepts it and your code remains readable and maintainable. Unlike some languages, Python variables don’t require an explicit type declaration; instead, names link to values dynamically at runtime.
Rules for Python Variable Names
Start with a letter or underscore:
Valid names begin withA–Z,a–z, or_. They cannot start with a digit.Allowed characters:
After the first character, a variable name may include letters, digits (0–9), or underscores (_).No spaces or special characters:
Names cannot contain spaces, hyphens (-), or other operators like!,%, and*.Case-sensitivity:
Variable names are case-sensitive; for example,age,Age, andAGEare distinct identifiers.Avoid keywords and built-in names:
Python keywords (likeif,for,while,class, etc.) and built-in function names (print,list, etc.) should not be used as variable names.No length limit:
Python allows variable names of arbitrary length, though very long names can reduce readability.
Examples of Valid & Invalid Variable Names
Valid Examples
These follow the naming rules and will not cause syntax errors.
Invalid Examples
These raise errors because they violate naming rules.
Python Naming Conventions (Style)
Although rules define what can be a variable name, conventions improve readability, especially in collaborative code:
Snake Case (Recommended)
Use lowercase letters and underscores to separate words:
This is the standard style recommended by Python’s official style guide (PEP 8).
Lowercase Variables
Prefer lowercase identifiers for variable names. Uppercase is typically reserved for constants:
Uppercase with underscores indicates constants by convention.
Note: Other styles like camelCase and PascalCase exist, but for most Python code, snake_case is preferred unless working in a context that already uses another convention.
Why Naming Conventions Matter
While Python will execute code regardless of naming style, following conventions:
Improves readability of your code
Makes collaboration easier
Helps others (and future you) quickly understand purpose
Reduces ambiguity and mistakes