CodeMIRAI
0 XP

Variables

2 min read 5 runnable examples Quiz included

A variable is a name that refers to a value. You create one by assigning a value with =.

NamesValues in memoryage30intname"Asha"strprice19.99floatage = 30 makes the name age point at the value 30
A variable is a name attached to a value. Assigning again moves the name to a new value; the old one is forgotten.
Python
name = "Asha"
age = 21
height = 1.65

print(name)
print(age)
print(height)

Think of a variable as a label stuck on a value. age = 21 means "the label age now points at the value 21".

Variables can change

That is why they are called variables. Assign a new value and the label moves to it:

Python
score = 10
print(score)

score = 25
print(score)

score = score + 5     # use the current value to make a new one
print(score)

The = sign does not mean "equals" as in maths. score = score + 5 means "work out score + 5, then make score refer to the result".

Naming rules

A variable name:

  • can contain letters, digits and underscores (_),
  • cannot start with a digit (2nd_place is an error),
  • cannot be a Python keyword such as if, for or class,
  • is case-sensitive (total and Total are different).

The Python convention is snake_case: lower-case words joined by underscores.

Python
first_name = "Leo"        # good: clear, snake_case
total_price = 49.99       # good
x = 49.99                 # works, but says nothing
print(first_name, total_price)

Several at once

Python can assign several variables in one line:

Python
x, y, z = 1, 2, 3
print(x, y, z)

a = b = 0             # both refer to 0
print(a, b)

# swap two values without a temporary variable
x, y = y, x
print(x, y)

Using a name before assigning it

Python
print(points)

A NameError means you used a name Python has never seen. Check the spelling, and make sure the assignment runs first.

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.