Variables
When a program is a sequence of assignments, you can follow the value of every variable by working down it one line at a time. After each assignment, write down the value that each variable now holds. Any variables on the right of an assignment use the values they hold at that moment, then the result replaces the value of the variable on the left.
Work out the right-hand side first, then store the result in the variable named on the left. Storing a value removes whatever that variable held before, so the next line sees the new value rather than the old one.
crates = 18
bottles = crates * 6
crates = 12
bottles = crates * 6
print(bottles)Output:
72| After this line | crates | bottles |
|---|---|---|
| 1 | 18 | - |
| 2 | 18 | 108 |
| 3 | 12 | 108 |
| 4 | 12 | 72 |
Line 2 uses the value held by crates at that point, 18, so bottles becomes 108. Line 3 replaces the 18 in crates with 12, so the 18 has gone. Line 4 works out crates * 6, which is 12 * 6, so bottles becomes 72 in place of 108. A dash in the table means the variable has not been given a value yet.
When a line prints a variable, the value shown is the one the variable holds when that line runs. A later assignment does not change what has already been printed.
slices = 24
people = slices // 3
print(people)
slices = 18
people = slices // 3
print(people)Output:
8
6people has been given the value 8 before line 3 prints it, so 8 appears. Line 4 replaces slices with 18, and line 5 recalculates people as 6, so the final print shows 6. The 8 printed earlier stays as 8.
OCR GCSE Computer Science · Variables