Algorithms
Arithmetic operators are the symbols in an algorithm or program that tell the computer to carry out a mathematical calculation on values. Each one takes the values either side of it and produces a new value, which can be stored in a variable or printed.
You need to know seven of them, and in Python 3 each one has a fixed symbol:
+) — puts values together, such as combining two amounts-) — finds the difference between values*) — works out repeated equal groups/) — shares a value out, and the answer may have a fractional part%) — gives the whole-number remainder left over after a division//) — gives the whole-number part of a division**) — raises a value to a powerArithmetic operators are only one family of operators. Relational operators compare two values, and logical operators work with conditions, so the symbol in front of you shows which family it belongs to.
| Type of operator | Job | Examples |
|---|---|---|
| Arithmetic | Calculates a new value from values | +, *, // |
| Relational | Compares two values, giving True or False | <, >=, != |
| Logical | Combines conditions, or reverses one | and, or, not |
The single = used in an assignment is not an arithmetic operator either — it stores the result of a calculation in a variable, while == is relational because it compares.
A school books a coach for £216 and fills it with 32 students and 4 staff. Adding the two groups is arithmetic, and dividing the cost by the number of people is arithmetic too, so the program below calculates and prints the cost for each person.
coach_cost = 216
students = 32
staff = 4
people = students + staff
cost_each = coach_cost / people
print(cost_each)Output:
6.0In Python 3, four of the arithmetic operators do everyday maths: addition, subtraction, multiplication and division. Each one is a single symbol, and the computer works out the calculation when it runs the line of code.
| Calculation | Symbol | Example |
|---|---|---|
| Addition | + | sweets = 14 + 9 |
| Subtraction | - | sweets = 14 - 9 |
| Multiplication | * | sweets = 14 * 9 |
| Division | / | sweets = 14 / 9 |
Multiplication uses the asterisk * because a keyboard has no multiplication sign. Python cannot read 14 x 9, so typing x instead of * stops the program with a syntax error. Always type *.
Subtraction can give a negative result. If a shop has 26 chocolate bars and sells 31, then bars = 26 - 31 stores the value -5. A negative value is a perfectly valid number, so the program keeps running. The minus sign shows the value is below zero.
Division with / gives a result that may have a fractional part. Sharing 45 stickers between 8 players gives 45 / 8, which is 5.625. This is not the same as integer division //, which keeps only the whole-number part and gives 5. Even when the numbers divide exactly, / still answers with a decimal: 20 / 4 gives 5.0, not 5. Use / when you need the exact share, and // when you need only whole stickers each.
biscuits = 52
friends = 6
print(biscuits / friends)
print(biscuits - 70)
print(biscuits * friends)Output:
8.666666666666666
-18
312
Change either number and the results change, but division with / still gives a decimal answer while subtraction can still drop below zero.
For positive whole numbers, integer division (written //) divides one whole number by another and keeps only the whole-number part of the answer, discarding the remainder. Modulus (written %) gives you that remainder. Both are arithmetic operators in Python 3, and they are closely linked: one gives the quotient and the other gives the remainder from the same division.
Picture 29 sweets shared equally between 6 people. Each person gets 29 // 6 = 4 sweets, because 6 fits into 29 four whole times. There are 5 sweets left over, so 29 % 6 = 5. The % symbol means modulus here — it has nothing to do with percentages.
With positive whole numbers, integer division does not round to the nearest whole number. 29 // 6 is 4, even though 29 ÷ 6 is about 4.83, which is nearer to 5. The remainder is simply discarded. If you used / instead, you would get 4.8333…, which keeps the fractional part.
The quotient and the remainder both come from the same division, so they always link back to the number you started with:
quotient × divisor + remainder = dividend
For the sweets: 4 × 6 + 5 = 29. You can use this to check either answer. If dividing by 8 gives a quotient of 7 and a remainder of 3, the original number must have been 7 × 8 + 3 = 59.
sweets = 29
people = 6
each = sweets // people
leftover = sweets % people
print("Each person gets " + str(each))
print("Left over: " + str(leftover))Output:
Each person gets 4
Left over: 5
The program prints the whole-number share and the leftover amount, which are the quotient and the remainder of the same division.
Exponentiation means raising a base value to a power by repeated multiplication. The exponent tells you how many copies of the base are multiplied together. In 4 ** 3, the base is 4 and the exponent is 3, so the calculation is 4 × 4 × 4, which gives 64.
In Python 3, exponentiation is written with **. The base comes first, then the two asterisks, then the exponent. For example, 6 ** 2 means 6 × 6 and gives 36. Because the exponent counts copies of the base, 6 ** 2 uses two 6s, not one.
Do not use ^ for exponentiation in Python 3. Even though ^ is sometimes used for powers in maths, Python does not treat it as a power operator. To calculate 2 × 2 × 2 and get 8, you must write 2 ** 3, not 2 ^ 3.
Each fold of a sheet of paper doubles the number of layers, so the number of layers is 2 multiplied by itself once for every fold — 2 raised to the power of the number of folds. This program asks for the number of folds and works out the layers using **.
folds = int(input('Enter number of folds: '))
layers = 2 ** folds
print(layers)Output when the user types 5:
Enter number of folds: 5
32When an expression contains more than one arithmetic operator, the computer does not simply work from left to right. It follows order of precedence: rules that decide which calculation is done first. Change the order and you change the value produced, so every expression in an algorithm must be worked through in the right sequence.
The usual order is remembered as BIDMAS: brackets, indices (powers), then division and multiplication, then addition and subtraction. Anything in brackets is calculated first, so brackets are how you override the normal order when you want a different result.
Exponentiation, written with **, is finished before any division or multiplication. In 2 + 5 * 3 ** 2 the power is done first (3 ** 2 is 9), then 5 * 9 is 45, and finally 2 is added to give 47. Writing (2 + 5) * 3 ** 2 gives 63 instead, because the bracketed addition is now first. Integer division // and modulus % sit on the same level as * and /.
Multiplication and division carry equal weight, so when they appear together you work from left to right: 36 / 4 * 3 is 9 * 3 = 27, not 36 / 12 = 3. Addition and subtraction also share a level and run left to right: 50 - 15 - 10 is 35 - 10 = 25, not 50 - 5 = 45. Even so, both addition and subtraction are always done after division and multiplication unless brackets say otherwise.
Reading an algorithm line by line, replace each symbol with its correct meaning and apply these rules before storing the result in a variable.
shirt = 12
shorts = 8
discount = 5
order = (shirt + shorts) * 2 - discount
print(order)Output:
35
Here the brackets are calculated first, so the two prices are added before being doubled, and the discount is only taken away at the end. Without the brackets, shorts * 2 would be worked out before the addition and the total would be different.
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.
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... | Operator | Example 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