Variables
age = 15age = 15 makes a box labelled age and puts 15 inside it.
1Level 1 · BasicsBasics
Programs need to remember things: a name, a score, a price. A variable is a name that stores a value so you can use it later.
Think of a labelled box
Picture a box with a label on it. The label is the variable's name, and what's inside is its value. You create a variable with a single equals sign:
age = 20 name = "Rahim"
Read = as "gets" or "is set to", not "equals". age = 20 means "age gets the value 20". Once a variable exists, write its name (without quotes) to use the value:
print(name, "is", age) # Rahim is 20
Changing a variable
Variables can change; that's why they're called variables. Assigning again replaces the old value:
score = 10 score = score + 5 # take the old score, add 5, store it back print(score) # 15
The shortcut score += 5 does the same thing. There are also -=, *= and /=.
Naming rules
| Allowed | Not allowed |
|---|---|
total, total_2, _hidden | 2total (can't start with a digit) |
first_name | first-name, first name (no dashes or spaces) |
my_class | class, if, for (reserved keywords) |
Names are case-sensitive, so Age and age are two different variables. Python programmers use snake_case (lowercase words joined by underscores). Choose names that explain themselves: price_per_kg beats p.
Several variables at once
a, b, c = 1, 2, 3 # three variables in one line x = y = 0 # both start at 0 a, b = b, a # swap two values
Storing what the user types
Practice problems give your program some input. input() reads one line of it, and you store that line in a variable:
name = input() # text, e.g. Rahim n = int(input()) # a whole number, e.g. 25 price = float(input()) # a decimal number, e.g. 12.5
Each input() reads the next line. Whatever is typed arrives as text, so wrap it in int(...) or float(...) when you need to do maths with it. You'll see why in the Data Types lesson, and the Input & Output lesson covers input() in full.
Key points: = stores a value in a name; assigning again replaces it; names use letters, digits and underscores but can't start with a digit; pick clear snake_case names.See it in actionVariables are labelled boxes
Watch each box get its value, and change when it is assigned again. Changed boxes flash.
Try it yourselfExample 1: Create and use variables
Change the values at the top and run again. Every line that uses them updates automatically.
Output appears hereExample 2: Updating a value
Each line takes the current value of coins, changes it, and stores it back.
Output appears hereLose a life
A game starts with 3 lives. Fill the blanks so the player loses one life and the program prints Lives left: 2.
lives = 3 lives 1 # lose one life print("Lives left:", )
Example 3: Swapping values
Python can swap two variables in one line, with no temporary variable needed.
Output appears hereA name with a space
This program should print Hello Mim, but Python stops with an error. Press Check to see the error, then fix the code.
Swap in one line
Fill the blanks so the two values swap and the program prints 9 5.
a, b = 5, 9 a, b = , print(a, b)
Example 4: Variables make code reusable
Change width and height once; every calculation follows.
Output appears hereGarden area
A garden is 12 metres long and 7 metres wide. Store the two sizes in variables named length and width, work out the area in a third variable, and print Area: 84.
Example 5: Reading input into variables
Each line in the Input box answers one input() call. Change the numbers and run again.
Output appears hereAdding to typed text
The program reads an age and should print next year's age. With the input 15 it should print Next year you will be 16, but it crashes. Fix it.
Example input15Expected outputNext year you will be 16
Add two numbers
Read two whole numbers, one per line, and print their sum like Sum: 10. Your program is checked with more inputs than the one shown.
Example input4
6Expected outputSum: 10
Coin wallet
Start with coins = 50. Spend 20 coins using -=, then earn 15 using +=. Print Coins: 45.
2Level 2 · IntermediateNames, references and constants
A variable is really a name tag stuck on a value. Several names can point at the same value.
Augmented assignment
score += 5 is short for score = score + 5. The same works for -=, *=, /= and //=.
Constants by convention
Python has no locked constants. By habit, names in CAPITALS such as PI = 3.14159 or MAX_MARKS = 100 mean "please don't change this".
Good names
Use snake_case, describe what the value means (total_price, not tp), and avoid built-in names such as list, str or sum, because you would hide the real function.
See it in actionOne box, many updates
Watch the value inside coins change with every augmented assignment.
Example 6: Updating with += and friends
Each line changes the same variable. Predict the final value before running.
Output appears hereExample 7: Why you shouldn't name a variable print
After print = 5, the real print() is hidden behind your variable. Remove the
Output appears here3Level 3 · AdvancedObjects, identity and mutability
Every value in Python is an object with a value and an identity. id(x) shows the identity as a number: two names with the same id point at the very same object.
Two names, one object
b = a does not copy anything. Both names now refer to the same object. Numbers and strings are immutable: they can never change. "Changing" one, as in a = a + 1, really makes a new object and moves the name a onto it, while b keeps pointing at the old one.
None means "nothing yet"
None is a special value for "no value". It is handy for a variable you will fill in later: result = None.
Dynamic typing and type hints
A name can point at any type, and later at another. Type hints like age: int = 15 don't change how the code runs; they document intent and let tools catch mistakes.
See it in actionTwo names on one number
At first a and b point at the same 10, so their ids match. a = a + 1 makes a new object, so a moves and b stays.
Example 8: Strings never change either
Adding "!" builds a new string for greeting. other still points at the old "Hi".
Output appears hereExample 9: Types can change; hints document intent
Python doesn't stop you from breaking a hint, so hints are for humans and checkers.
Output appears hereNameError: name 'x' is not defined. Check the spelling too: Score and score are different names.What does this program print?
x = 4 x = x * 2 x += 1 print(x)
50 graded problems are waiting in Topic Practice.