Python Reference ยท Numbers and Binary Data
Python arithmetic operators
Reference for Python arithmetic operators: +, -, *, /, //, %, ** and divmod(), with floor division and modulo for negatives, the power rules and sequence use.
Python's arithmetic operators work on numbers, and several of them double as sequence operators: + joins and * repeats strings, lists and tuples. The numeric ones are +, -, *, /, //, %, ** and @ (matrix multiplication, used by NumPy but not defined for built-in types).
The least obvious are floor division // and modulo %, which round toward negative infinity. That keeps one rule true for all numbers: a == (a // b) * b + a % b.
7 / 2 # 3.5 7 // 2 # 3 7 % 2 # 1 2 ** 10 # 1024
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
| Operator | Meaning | Notes |
|---|---|---|
a + b |
Addition, concatenation | Numbers, or two sequences of the same type. |
a - b |
Subtraction | Also set difference for sets. |
a * b |
Multiplication, repetition | "ab" * 3, [0] * n. |
a / b |
True division | Always returns a float (or complex). |
a // b |
Floor division | Rounds toward negative infinity. |
a % b |
Modulo | Result has the sign of b. |
a ** b |
Power | Right-associative; binds tighter than unary minus on its left. |
-a, +a |
Unary minus and plus | |
divmod(a, b) |
Tuple (a // b, a % b) |
One call instead of two. |
Raises: ZeroDivisionError for /, //, % and divmod() with a zero divisor, and for 0 ** -1. TypeError for unsupported operand types, such as "a" + 1.
Usage notes
- Floor, not truncate.
-7 // 2is-4, not-3. For truncation useint(a / b)ormath.trunc, though/on huge ints may lose precision. %takes the sign of the divisor.-7 % 2is1, and7 % -2is-1. It is great for wrapping indexes:i % len(items)is never negative when the length is positive.-2 ** 2is-4. The power operator binds tighter than a unary minus on its left. Write(-2) ** 2for 4.**is right-associative:2 ** 3 ** 2is2 ** 9, not8 ** 2.- Integer
**with a negative exponent gives a float (2 ** -1is0.5). A negative base with a fractional exponent gives a complex number. - Floats are inexact, so
0.1 + 0.2 != 0.3. For exact money usedecimal.Decimal. - Combine with
=:x += 1,x //= 2,x **= 2update a variable. For lists,+=extends in place, while+creates a new list. - The
floatresult of/can lose precision with very large ints; use//for exact integer division.