Sub topic 2
Arithmetic operators
This chapter assumes you can run a script or the REPL, and that you know the built-in int, float and bool types and simple assignment. It covers the arithmetic operators and the type of value each one returns. The next chapters cover division and floating-point precision in detail.
The operators
An operator combines operands into a new value. Python's arithmetic operators are:
| Operator | Meaning | Example | Result |
|---|---|---|---|
| `+` | addition | `3 + 4` | `7` |
| `-` | subtraction | `3 - 4` | `-1` |
| `*` | multiplication | `3 * 4` | `12` |
| `/` | true division | `6 / 3` | `2.0` |
| `//` | floor division | `7 // 2` | `3` |
| `%` | modulo (remainder) | `7 % 2` | `1` |
| `**` | exponentiation | `2 ** 3` | `8` |
| `-x`, `+x` | unary negation, unary plus | `-5` | `-5` |
The operators +, - and * are binary, which means they take two operands. The signs - and + are also unary, which means they take one operand.
Which type comes back
The type of the result depends on the operand types. If both operands are int, then +, -, *, // and % return an int. If either operand is a float, the result is a float. Python converts the int to a float first.
True division / is different. It returns a float even when both operands are integers.
print(3 + 4)
print(3 + 4.0)
print(6 / 3)
print(2 ** 10)
print(2 ** -1)
print(2 ** 100)
print(True + True)This prints 7, 7.0, 2.0, 1024, 0.5, 1267650600228229401496703205376 and 2.
Three details in that output are worth noting:
- A negative integer exponent returns a
float, because the result is usually not a whole number. inthas no size limit, so2 ** 100is exact. Afloathas a fixed precision.boolis a subclass ofint.Trueacts as1andFalseacts as0in arithmetic.
Common errors
Python does not convert strings to numbers for you. "3" + 4 raises a TypeError because str and int do not define addition with each other. Convert explicitly with int("3") + 4.
Dividing by zero raises ZeroDivisionError. This applies to /, // and %, for integers and floats alike.
Applying it
Arithmetic operators are used constantly in ordinary code. A common case is converting seconds to minutes and seconds:
total_seconds = 135
minutes = total_seconds // 60
seconds = total_seconds % 60
print(f"{minutes}:{seconds:02d}")This prints 2:15. Floor division gives whole minutes and modulo gives the remainder. The next chapter explains how both behave with negative numbers.
Exercise
What value and type does each expression produce: 10 / 2, 10 // 2, and 2 ** -2?
Show answer
10 / 2 is 5.0, a float, because true division always returns a float. 10 // 2 is 5, an int, because both operands are ints. 2 ** -2 is 0.25, a float, because a negative integer exponent returns a float.