Menu

Arithmetic Operators

Arithmetic in Algorithms

In an algorithm, arithmetic operators are used in two ways: to calculate a brand new value, and to update a value that is already stored in a variable.

The updating job is easy to miss. A line such as total = total + 2.50 looks as though it does nothing, but the computer works out the right-hand side first, then stores the answer back into total. So each time that line runs, the stored value grows. A line like lives = lives - 1 works the same way in reverse. Repeating updates like these is how an algorithm keeps a running total, a score or a count as it works through its steps.

Match the operator to the calculation

Before you write a line, decide what the calculation actually means. Choosing the wrong operator still lets the algorithm run, but the value it stores will be wrong.

The algorithm needs to...OperatorExample line
build a running total+spent = spent + 3.20
find how far apart two values are-gap = target - score
count several equal groups*cost = tickets * 7
share out and allow a fraction/each = length / 4
find how many whole groups fit//boxes = cakes // 12
find what is left over%left = cakes % 12
raise a value to a power**grown = 2 ** 6

Worked example: a drama club has 47 members and each minibus holds 6. Writing 47 // 6 gives 7 full minibuses, and 47 % 6 gives 5 members left to travel in a smaller vehicle. Using / would give 7.833..., which is not a number of minibuses anyone can book.

Here the same ideas work together. Two ticket counts are read in, multiplied by their prices, added to form a total, and then that stored total is updated with a discount:

adult = int(input())
child = int(input())
total = adult * 8 + child * 5
total = total - 3   # online booking discount
print(total)

Output when the user types 3, 2:

3
2
31

Practise this