CodeBlanks Logo Icon CodeBlanks

Naming variables

Learn valid variable naming rules.

Variable naming rules

A variable name must start with a letter or underscore; it cannot start with a digit. It can contain letters, digits and underscores.

Valid names: user_age, _count, total2. Invalid names: 2nd (starts with a digit), user-age (has a hyphen), class (reserved word).

Python is case sensitive: age and Age are different variables. Reserved words (if, for, class, def) cannot be used.

The snake_case convention

The Python community convention is to use snake_case: lowercase words separated by underscores.

  • user_age not userAge
  • total_price not totalprice
  • is_valid not isvalid

For boolean variables the is_ or has_ prefix is common. This convention is defined in PEP 8.

Practice Declare two variables

Assign "Alex" to user_name, assign 25 to user_age. Then print print(user_name).

Starter code

main.py
# Declare the variables

Sample solution

main.py
user_name = "Alex"
user_age = 25
print(user_name)

Expected output

Alex

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is a valid variable name?

  • 2nd_place
  • total_count Correct answer
  • user-name
  • class

Explanation: total_count starts with a letter and uses an underscore.

2 Declare the age variable

Question
user_____ = 25
Answer
user_age = 25

Explanation: user_age = 25 follows snake_case naming.

3 Match the naming principles

Term Meaning
Starts with a letter Valid name
Starts with a digit Invalid name
Reserved word Cannot be used
snake_case Python convention

All lessons in Beginner