Sub topic 2
Arithmetic operators
This chapter assumes you can run a script or the REPL, know the built-in types int, float, str, bool, list and dict, and can assign to variables. It covers the operators that compute numbers: what each one does, what type it returns, and where it fails. Division, floor division and modulo get a full treatment in the next chapter, so they appear here only in summary.
The operators
Python has seven binary arithmetic operators and two unary ones. A binary operator takes two operands, as in a + b. A unary operator takes one, as in -a.
| Operator | Name | Example | Result |
|---|---|---|---|
| `+` | addition | `7 + 3` | `10` |
| `-` | subtraction | `7 - 3` | `4` |
| `*` | multiplication | `7 * 3` | `21` |
| `/` | true division | `7 / 2` | `3.5` |
| `//` | floor division | `7 // 2` | `3` |
| `%` | modulo | `7 % 2` | `1` |
| `**` | exponentiation | `7 ** 2` | `49` |
| `-x`, `+x` | unary negation, unary plus | `-(-3)` | `3` |
A matrix multiplication operator, @, also exists. No built-in type implements it. Libraries such as NumPy do.
print(7 + 3)
print(7 - 3)
print(7 * 3)
print(7 / 3)
print(7 // 3)
print(7 % 3)
print(7 ** 3)The output is 10, 4, 21, 2.3333333333333335, 2, 1 and 343.
Which type comes back
The result type depends on the operand types. Python converts the "narrower" operand to the "wider" one before computing. The order is int, then float, then complex.
Some consequences follow from this order:
+,-,*,//,%and**with twointoperands give anint. There is one exception:**with a negative exponent gives afloat./always gives afloat, even when the division is exact.4 / 2is2.0.- If either operand is a
float, the result is afloat, so2 + 3.0is5.0. boolis a subclass ofint.True + Trueis2, andTrueacts as1in arithmetic.
print(type(4 / 2), 4 / 2)
print(type(2 + 3.0), 2 + 3.0)
print(True + True)
print(2 ** -1)
print((1 + 2j) * (3 - 1j))The output is <class 'float'> 2.0, <class 'float'> 5.0, 2, 0.5 and (5+5j).
Integers have no fixed size
Python's int grows as needed. It does not overflow the way a 32-bit or 64-bit integer does in C or Java. Only available memory limits it.
print(2 ** 100)
print(10 ** 20 + 1)The first line prints 1267650600228229401496703205376. The second prints 100000000000000000001.
Floats are different. A float is a fixed-size 64-bit value, and it has limits. Multiplication that goes too far gives inf, but ** raises OverflowError.
print(1e308 * 10)
try:
print(2.0 ** 10000)
except OverflowError:
print("OverflowError")Exponentiation details
** has three behaviours worth remembering.
First, it is right-associative. 2 ** 3 ** 2 means 2 ** (3 ** 2), which is 512, not 64.
Second, it binds tighter than unary minus on its left. -2 ** 2 is -(2 ** 2), which is -4. The precedence chapter explains the full rules.
Third, the built-in pow accepts a third argument for modular exponentiation. pow(a, b, m) computes (a ** b) % m without building the huge intermediate number, so it is fast even for very large exponents.
print(2 ** 3 ** 2)
print((2 ** 3) ** 2)
print(-2 ** 2)
print((-2) ** 2)
print(pow(2, 10, 1000))
print(pow(3, 4, 5))The output is 512, 64, -4, 4, 24 and 1.
Errors you will meet
Two exceptions cover most arithmetic failures.
ZeroDivisionError is raised by /, // and % when the right operand is zero, for both int and float.
TypeError is raised when the operand types do not support the operator. The typical case is mixing a str with a number.
try:
print(1 / 0)
except ZeroDivisionError:
print("ZeroDivisionError")
try:
print("1" + 1)
except TypeError:
print("TypeError")
print(int("1") + 1)The last line prints 2. Convert the string first. Python does not convert types silently between strings and numbers.
Unary plus and the missing `++`
Unary - negates a number. Unary + returns the number unchanged for built-in types. Python has no ++ or -- operators. ++x parses as +(+x), which is just x, and it does not change the variable. x++ is a syntax error. Write x += 1 instead, as covered in the assignment chapter.
x = 5
print(++x)
print(x)
x += 1
print(x)The output is 5, 5 and 6.
When floats are the wrong tool
Because floats are binary approximations, 0.1 + 0.2 does not equal 0.3 exactly. The float precision chapter covers this in detail. When you need exact results, use a number type built for it. Both of these are in the standard library and work with the same operators.
from decimal import Decimal
from fractions import Fraction
print(Decimal("0.1") + Decimal("0.2"))
print(Fraction(1, 3) + Fraction(1, 6))
try:
print(Decimal("0.1") + 0.2)
except TypeError:
print("TypeError")The output is 0.3, 1/2 and TypeError. Decimal refuses to mix with float on purpose, so imprecise values cannot slip in unnoticed. Build a Decimal from a string, as in Decimal("0.1"). Building it from the float 0.1 captures the float's error.
Checking your understanding
Exercise
What do 2 ** 3 ** 2 and -3 ** 2 print, and why?
Show answer
They print 512 and -9. The operator ** is right-associative, so 2 ** 3 ** 2 is 2 ** (3 ** 2), which is 2 ** 9. Also, ** binds tighter than unary minus, so -3 ** 2 is -(3 ** 2).
Exercise
What type and value does 6 / 3 + True produce?
Show answer
It produces the float 3.0. The division 6 / 3 is 2.0 because / always returns a float. True counts as 1, so 2.0 + 1 is 3.0.
Exercise
A script computes total = "5" + 3. What happens, and what is the fix if you want 8?
Show answer
It raises TypeError because + is not defined between a str and an int. Convert the string first: total = int("5") + 3.