Variables
A name refers to a value and can be rebound.
A variable is a name that refers to a value. The = sign creates the link: the value on the right is computed, and the name goes on the left.
city = "Prague"
year = 2026
print(city, year)
= is not the "equals" from maths, it means "call this value by this name". A check for equality uses two signs: ==.
A name can be rebound to another value, even one of a different type. Python allows it, but in tidy code one variable holds one kind of thing: if count was a number, let it stay a number.
count = 3
count = count + 1
print(count) # 4
The right side uses the old value, and the name on the left gets the new one. count += 1 does the same thing in a shorter form.
The rules for names: letters, digits and _, but a name cannot start with a digit. Case matters: name and Name are different variables. Keywords of the language (if, for, class, def and others) cannot be names. In Python names are written in snake_case: user_name, total_price. A good name explains the meaning: price is better than p, and price_with_tax is better than price2.
Several names can be bound in one line, and two variables can swap values without a temporary one:
a, b = 1, 2
a, b = b, a
print(a, b) # 2 1
If you use a name that has not been created yet, Python stops with NameError: name '...' is not defined. Most often it is a typo, or a variable that is created further down the code than where it is used. type(year) tells you the type of a value and returns <class 'int'>.
Practice
A valid name
Which variable name is valid in Python?
- user_name
- 2users
- user-name
- class
Swapping values
What does the program print?
a = 1 b = 2 a, b = b, a print(a, b)Purchase total
The program already has the variables price and count. Print one number: the cost of the whole purchase.