Variables
A variable is a name that refers to a value. You create one by assigning a value with =.
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_placeis an error), - cannot be a Python keyword such as
if,fororclass, - is case-sensitive (
totalandTotalare 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.