Lesson 2 of 12 · about 15 minutes
Variables and numbers
Giving values a name
A variable is a name that refers to a value. You create one with a single equals sign:
age = 12
name = "Sam"
print(name, "is", age)Sam is 12Read age = 12 as "age now refers to 12". The equals sign means assign, not "is equal to". The name goes on the left, the value on the right.
Changing a variable
A variable can be given a new value at any time. The new value replaces the old one:
score = 0
print(score)
score = 10
print(score)
score = score + 5
print(score)0
10
15The last assignment looks odd at first. Python works out the right-hand side first (score + 5, which is 15), then stores the result back in score.
Quick check
What does this print?
score = 3
score = score * 2
print(score)Naming rules
Variable names can contain letters, digits and underscores, but cannot start with a digit or contain spaces. Python programmers usually write names in lowercase with underscores between words:
total_price = 42
player_2_score = 7Choose names that say what the value means. total_price is much easier to understand later than tp or x.
Two kinds of numbers
Python has whole numbers, called integers (int), and numbers with a decimal point, called floats (float). The type function tells you which one you have:
print(type(7))
print(type(7.5))<class 'int'>
<class 'float'>Doing maths
| Operator | Meaning | Example | Result |
|---|---|---|---|
| + | add | 7 + 2 | 9 |
| - | subtract | 7 - 2 | 5 |
| * | multiply | 7 * 2 | 14 |
| / | divide | 7 / 2 | 3.5 |
| // | divide, rounding down | 7 // 2 | 3 |
| % | remainder | 7 % 2 | 1 |
| ** | power | 7 ** 2 | 49 |
Plain division with / always gives a float, even when the answer is whole: 8 / 2 is 4.0. Use // when you want a whole number.
// and % are a useful pair. Together they split a number into "how many whole groups" and "how many left over":
eggs = 14
boxes = eggs // 6
left_over = eggs % 6
print(boxes, "full boxes and", left_over, "eggs left over")2 full boxes and 2 eggs left overPython follows the usual order of operations, so 2 + 3 * 4 is 14. Use brackets when you want something worked out first: (2 + 3) * 4 is 20.
Quick check
What are 17 // 5 and 17 % 5?
Exercise 1: Area of a rectangle
Create a variable called area that holds the width multiplied by the height, then print it.
Exercise 2: Hours and minutes
Turn 135 minutes into hours and minutes. Store them in variables called hours and minutes, then print 2 hours and 15 minutes.
Lesson 2 complete
You finished variables and numbers and passed every exercise.
What you learned
name = valuecreates or updates a variable.- Integers are whole numbers; floats have a decimal point.
/gives a float,//rounds down, and%gives the remainder.