After this lesson you can do the maths a program needs: totals, averages, remainders and powers, and you will know which part of a long expression Python works out first.
The seven operators
Python uses familiar symbols for most arithmetic. Here is the full set, applied to two numbers from a small shop: 17 apples and 5 baskets.
apples = 17
baskets = 5
print(apples + baskets)
print(apples - baskets)
print(apples * baskets)
print(apples / baskets)
print(apples // baskets)
print(apples % baskets)
print(apples ** 2)22
12
85
3.4
3
2
289Going through the output in order: addition, subtraction and multiplication behave as you would expect. The next three need a closer look.
Three kinds of division
The single slash / is true division. It always returns a float, even when the answer is a whole number.
print(10 / 2)
print(type(10 / 2))5.0
<class 'float'>Double slash // is floor division. It answers "how many whole times does this fit?" and throws away the rest. The percent sign % is the modulo operator and gives exactly the part that was thrown away: the remainder. Together they split a quantity into groups and leftovers.
apples = 17
per_basket = 5
full_baskets = apples // per_basket
leftover = apples % per_basket
print(full_baskets, "full baskets and", leftover, "left over")3 full baskets and 2 left overA very common use of % is checking whether a number is even. If n % 2 is 0, the number divides by two with nothing left.
print(14 % 2)
print(15 % 2)0
1With negative numbers, floor division rounds towards minus infinity, not towards zero, so -7 // 2 is -4. This surprises people used to other languages.
print(-7 // 2)
print(-7 % 2)-4
1Powers
The ** operator raises a number to a power. 3 ** 2 is three squared, and 2 ** 10 is 1024. A fractional power gives roots: 16 ** 0.5 is the square root of 16, returned as a float.
print(2 ** 10)
print(16 ** 0.5)1024
4.0Order of operations
When an expression mixes operators, Python works in a fixed order, the same one you learned in school. Brackets come first. Then powers. Then multiplication, division, floor division and remainder, which share one level and are worked from left to right. Last come addition and subtraction.
print(2 + 3 * 4)
print((2 + 3) * 4)
print(2 * 3 ** 2)
print(100 - 10 - 5)14
20
18
85The last line shows left-to-right working: it is (100 - 10) - 5, which is 85. When an expression is not obvious at a glance, add brackets. They cost nothing and make your intent clear to the next reader.
Updating a variable
Programs constantly change a value based on its old value, such as adding to a running total. Writing the name twice is tedious, so Python has shorthand operators.
stock = 40
stock -= 5
stock += 12
stock *= 2
print(stock)94Each line reads the current value, applies the operation, and stores the answer back. There is one for every operator: +=, -=, *=, /=, //=, %= and **=. Python has no ++ or --. Use += 1 and -= 1 instead.
Dividing by zero
Maths does not allow division by zero, and neither does Python. The program stops with an error:
print(10 / 0)ZeroDivisionError: division by zeroThe same error appears for // and % with a zero on the right. When a divisor comes from user input or a calculation, test it first, which you will learn to do with if statements in the control flow section.
Reading an expression like Python does
When a calculation gives a surprising answer, slow down and work through it the way Python does. First mark the brackets and solve what is inside them. Then look for powers. Then go left to right through multiplication, division, floor division and remainder. Finally go left to right through addition and subtraction. Writing the intermediate steps on paper, or printing them one at a time in a program, quickly shows where your idea and Python's differ. It also helps to give the pieces names. A line such as total = price * quantity followed by with_tax = total * 1.2 is far easier to check than one long expression doing everything at once.
Common mistakes
- Expecting
/to give an integer.10 / 2is5.0. Use//when you want a whole number. - Forgetting that
**binds tighter than a minus sign on its left. In-2 ** 2the answer is-4, because the power is worked out first. Write(-2) ** 2for 4. - Writing
x =+ 1instead ofx += 1. The first assigns positive one to x. Put the operator first. - Using
^for powers. In Python^is a different operation called bitwise XOR, so2 ^ 3is 1, not 8. - Mixing up
%with percentages.50 % 200is not "fifty percent of 200". To find a percentage, multiply:200 * 50 / 100.
A video version of this topic is in the video course at /learn/python/.
Exercise
A school has 47 students and each minibus seats 12. Print how many full buses are needed, how many students are left over, and how many buses are needed in total if the leftover students also get a seat. Do not use any import.
Show a possible answer
students = 47
seats = 12
full = students // seats
left = students % seats
total = full + (1 if left else 0)
print(full, left, total)3 11 4The expression 1 if left else 0 gives 1 when there are leftovers and 0 when there are none. You will study that form in the control flow lessons. A shorter trick for the total is -(-students // seats).
Key points
- Python has seven arithmetic operators: + - * / // % and **.
- A single slash always gives a float. Double slash gives a whole-number quotient, and % gives the remainder.
- Python follows the usual order of operations: brackets, then **, then * / // %, then + -.
- Operators such as += and *= change a variable in place and save you from writing the name twice.
- Dividing by zero raises a ZeroDivisionError, so check the divisor if it can be zero.