Python Variable Names

Python has clear rules for which variable names are legal and widely followed conventions for which names are readable.

The rules

A valid variable name must start with a letter or an underscore, and the rest of the name may contain letters, digits, and underscores. Names cannot begin with a digit, cannot contain spaces or punctuation such as hyphens, and are case sensitive, so age, Age, and AGE are three distinct variables.

  • Must begin with a letter (a-z, A-Z) or an underscore ( _ ).
  • May contain only letters, digits (0-9), and underscores after the first character.
  • Cannot be one of Python's reserved keywords, such as if, for, class, or True.
  • Are case sensitive: total and Total refer to different variables.

Legal and illegal names

# Valid
user_name = "Sam"
_private = 10
level2 = 99

# Invalid (each line would raise a SyntaxError)
# 2level = 99
# user-name = "Sam"
# class = "A"
Note: Never name a variable after a built-in function such as list, sum, or str. It works, but it hides the original function for the rest of that scope and leads to confusing bugs.

Naming styles

Because you often need multi-word names, developers rely on consistent naming styles to keep code readable. The Python community strongly favours snake_case for ordinary variables, where words are lowercase and joined by underscores.

StyleExampleTypical use in Python
snake_caseuser_ageThe recommended style for variables and functions
camelCaseuserAgeCommon in other languages; rarely used for Python variables
PascalCaseUserAgeReserved by convention for class names
UPPER_CASEMAX_SIZEUsed for constants that should not change

Choosing a descriptive name is just as important as following the style. A name like days_remaining tells a reader far more than a bare d, and the small extra typing pays off every time the code is read again.

Readable names in practice

first_name = "Grace"
last_name = "Hopper"
MAX_LOGIN_ATTEMPTS = 3

full_name = first_name + " " + last_name
print(full_name)