WasiLearn Code
Python · Getting started

Variables — boxes with names

A variable is a box with a name on it. You put a value in the box, and from then on you can use the name instead of the value.

Making a variable

The = sign puts a value into a box. It's not "equals" like in maths — it means "store this":

name = "Bilal"
age = 13

print(name)
print(age)
output
Bilal
13

name and age are variables. Once they exist, print(name) means "print whatever is in the box called name".

Variables can change

That's why they're called variables — the value can vary. The box keeps whatever you put in last:

score = 0
print("Start:", score)

score = 10
print("After one game:", score)

score = score + 5
print("Bonus points:", score)
output
Start: 0
After one game: 10
Bonus points: 15

The last one is the line to stare at: score = score + 5 means "take what's in the box, add 5, put the result back". Nearly every program you'll ever write does this somewhere.

Naming rules

Python accepts almost any name, but three rules are enforced:

  • letters, numbers and underscores only — no spaces (high_score, not high score)
  • can't start with a number (player1 is fine, 1player is not)
  • capital letters matter: Name and name are two different boxes

And one rule enforced by other programmers: names should say what's in the box. s saves you a second of typing; score saves the next reader a minute of guessing. You in two weeks are the next reader.

Strings and numbers, again

Remember from lesson 1 that "13" and 13 are different things? Variables remember which one they hold:

apples = 3
message = "I have"

print(message, apples, "apples")
print(apples + 2)
output
I have 3 apples
5

Try changing apples = 3 to apples = "3" and running it again — the last line becomes an error, because text can't do maths. When something breaks, check what's actually in the box.

Your turn

Exercise 1

Create a variable called score with the value 7, add 3 to it the way the lesson showed, then print it. The output must be 10.

Prefer learning with a teacher?

WasiLearn Academy runs small-group classes covering this material, online and in Karachi.

See the classes