Variables
An update changes a variable using the value it already holds. For example, passengers = passengers + 3 works out the current value of passengers, adds three, and stores the result back in passengers. Programs use this to keep a running total, count events, or take an amount away.
The right-hand side of = is worked out first, using the value the variable holds at that moment. The result then replaces the old value. So the variable name must be written on both sides: the right side uses the current value, and the left side names where the new value is stored. The old value is used before it is replaced.
A variable must already hold a value before you use it in an update. budget = budget - 4 cannot work if budget has never been set, because there is no current value to subtract 4 from, so the program stops with an error. Set budget = 20 first, and the update will run.
# The variable is used before it has been given a value
budget = budget - 4
print(budget)Output:
NameError: name 'budget' is not defined (line 2)A running total adds values up as a program runs. Start the total at zero, then keep adding to that same variable each time a new value arrives. The right-hand side uses the total as it stands, and the result becomes the new total.
# Cake sale takings for the school trip
funds = 0
funds = funds + 18
funds = funds + 23
print("Trip fund so far:", funds)Output:
Trip fund so far: 41If funds holds 18 and the next line is funds = funds + 23, the right side works out 18 + 23 = 41 and stores 41 back in funds. The 18 is replaced, but it was used in the sum. Without starting at zero, the first update has no total to add to and the program fails.
OCR GCSE Computer Science · Variables
OCR GCSE Computer Science · Arithmetic Operations
OCR GCSE Computer Science · Count-Controlled Iteration
OCR GCSE Computer Science · Condition-Controlled Iteration