Arithmetic in Python looks like the arithmetic that you already know, and then it does not. The division operators behave differently from most languages. Exponentiation is done before a minus sign. Floor division rounds down towards negative infinity and not towards zero. And round() sends a tie to the even neighbour. These are small rules, and each one has cost somebody an afternoon of confusion. This lesson pins them down one by one.
The previous lesson in this module covered "Python Data Types Explained: int, float, str, bool", and the next lesson in this module is about "String vs Numeric Operations: What Actually Changes".
What arithmetic operators does Python have?
| Operator | Meaning | 17 and 5 |
|---|---|---|
+ | addition | 22 |
- | subtraction | 12 |
* | multiplication | 85 |
/ | true division, always a float | 3.4 |
// | floor division, drops the decimal part | 3 |
% | remainder after floor division | 2 |
** | exponentiation | 1419857 |
divmod(a, b) | quotient and remainder together | (3, 2) |
a, b = 17, 5
print('a + b ->', a + b)
print('a - b ->', a - b)
print('a * b ->', a * b)
print('a / b ->', a / b)
print('a // b ->', a // b)
print('a % b ->', a % b)
print('a ** b ->', a ** b)
print('divmod ->', divmod(a, b))
print('abs(-a) ->', abs(-a))
print('round(2.5) ->', round(2.5), '| round(3.5) ->', round(3.5))
The last line needs a second look. round(2.5) gives 2 and round(3.5) gives 4. Python sends a tie to the nearest even number, and that rule stops repeated rounding from drifting. If you want a different rule, use the decimal module, because it lets you choose exactly how ties are handled.
Python also has bitwise operators for working with the bits inside integers. & is and, | is or, ^ is exclusive or, << and >> shift bits, and ~ inverts them. They work on whole numbers and not on text or booleans, and they are how you set and clear individual flags.
How does operator precedence actually work?
Precedence decides which operator acts first when several of them appear in one expression. The order that you need most often is short. ** comes first, then *, /, //, and %, then + and -, and then comparisons. Everything else, including and and or, comes later still.
Two results surprise people who learned arithmetic in school. A minus sign in front of a number binds less tightly than exponentiation, so -2 ** 2 means -(2 ** 2) and equals -4 and not 4. And exponentiation works from the right, so 2 ** 3 ** 2 means 2 ** (3 ** 2), which is 512 and not 64.
print('-2 ** 2 ->', -2 ** 2)
print('(-2) ** 2 ->', (-2) ** 2)
print('2 ** 3 ** 2 ->', 2 ** 3 ** 2)
print('2 + 3 * 4 ->', 2 + 3 * 4)
print('(2 + 3) * 4 ->', (2 + 3) * 4)
print('10 - 4 - 3 ->', 10 - 4 - 3)
print('100 / 10 / 5 ->', 100 / 10 / 5)
print('7 // 2 % 3 ->', 7 // 2 % 3)
Multiplication, division, and subtraction all work from the left, which is why 100 / 10 / 5 is 2.0 and not 20. When you are not sure how a line will be read, add brackets. They cost nothing, and they turn a line that you have to decode into a line that you can read at once.
Python also has an augmented form for every arithmetic operator: +=, -=, *=, /=, //=, %=, and **=. Each one puts the result back into the same name. Each one keeps the precedence of the operator that it wraps, so x **= 2 squares the value. For a plain number these forms are handy. For a string, += adds to the end, and that is the fastest way to build a long string inside a loop.
What does / do differently from //?
/ always gives a float, even when the division is exact, because that is the honest answer to the question "how many times does this go into that". // gives a whole number by dropping the decimal part, and the direction in which it drops is where the surprise lives. It always moves towards negative infinity and never towards zero.
print('7 / 2 ->', 7 / 2)
print('7 // 2 ->', 7 // 2)
print('-7 // 2 ->', -7 // 2)
print('-7 % 2 ->', -7 % 2)
print('7 % -2 ->', 7 % -2)
print('divmod(7, 2) ->', divmod(7, 2))
print('divmod(-7, 2) ->', divmod(-7, 2))
print('7.5 // 2 ->', 7.5 // 2)
print('10 // 3 ->', 10 // 3, '| 10 / 3 ->', 10 / 3)
try:
print(10 / 0)
except ZeroDivisionError as error:
print('10 / 0 ->', error)
So -7 // 2 is -4, because floor division asks "what is the largest whole number that is not more than -3.5", and the answer is -4. The remainder takes the sign of the divisor, so -7 % 2 is 1. That keeps the useful rule that a == (a // b) * b + (a % b) always holds, and that rule is what makes divmod safe for splitting an amount into whole units and leftovers.
Floor division also works on floats, and then it gives a float back, so 7.5 // 2 is 3.0. It is not a rounding function. To round to a number of decimal places, use round().
What happens when arithmetic goes wrong?
Dividing by zero raises ZeroDivisionError for both integers and floats, and Python will not guess an answer for you. Integer arithmetic, on the other hand, has no ceiling at all. 10 ** 400 simply gives a number with 401 digits. Floats are the ones with limits. An operation that goes past their range raises OverflowError, and one that only goes too far gives infinity instead. Knowing this stops a strange result from looking like a mystery.
try:
print(10.0 ** 400)
except OverflowError as error:
print('float overflow ->', error)
print('1e308 * 10 ->', 1e308 * 10)
print('int arithmetic has no ceiling ->', len(str(2 ** 100)), 'digits')
There is a second kind of wrongness that raises no error at all, and that is floating point error which builds up over time. Adding numbers one at a time rounds the running total after every step, so a small value can disappear inside a large one. The standard library has a fully accurate option, and since Python 3.12 the built-in sum() has improved as well, because it now uses compensated summation to reduce this drift.
import math
from decimal import Decimal
from fractions import Fraction
tenths = [0.1] * 10
print('sum() of ten tenths ->', sum(tenths))
print('math.fsum() ->', math.fsum(tenths))
# A tiny value between two enormous ones: sum() loses it, fsum() keeps it.
mixed = [1e-16, 1.0, 1e16]
print('sum() ->', sum(mixed))
print('math.fsum() ->', math.fsum(mixed))
print('Fraction ->', Fraction(1, 3) + Fraction(1, 6))
print('Decimal ->', Decimal('0.1') * 3)
Use math.fsum() when you add many floats and you want the best answer that you can get. Use Fraction when the values are ratios that you want to hold exactly. Use Decimal when the values are money, or anything else that a customer will read on an invoice.
Your turn: build a change calculator
- Write a script that takes a total price and the number of equal payments, and prints how much each payment is. Run it with 100 and 3, and notice that
100 / 3is not exactly 33.33. - Now use
Decimalinstead, built from strings, and print the same division. Write a comment that explains whyDecimal(100 / 3)is a worse choice thanDecimal('100') / Decimal('3'). - Add a line that splits a quantity into boxes and leftovers with
divmod(), for example 17 apples into boxes of 5. Check thatboxes * 5 + leftover == 17. - Print
-7 // 2andint(-7 / 2)next to each other. They give different answers, and the difference is floor division compared to cutting off the decimal part. - Finish by summing a list of one hundred values of
0.1twice: once withsum()and once withmath.fsum(). Print both, and write one sentence saying which one you would use in a reporting script.
Takeaways
/always gives a float, and//gives a whole number rounded towards negative infinity.- The remainder takes the sign of the divisor, so
a == (a // b) * b + (a % b)always holds. -2 ** 2is-4, and2 ** 3 ** 2is 512, because exponentiation works from the right and comes before a minus sign.- Integer arithmetic never overflows, and float arithmetic either raises
OverflowErroror gives infinity. - Use
math.fsum()for float sums,Fractionfor exact ratios, andDecimalfor money.