What are the arithmetic operators in Python and how do they behave with different types?
Python provides these arithmetic operators:
| Operator | Operation | Example |
|---|---|---|
+ |
Addition | 5 + 3 = 8 |
- |
Subtraction | 5 - 3 = 2 |
* |
Multiplication | 5 * 3 = 15 |
/ |
True division | 7 / 2 = 3.5 |
// |
Floor division | 7 // 2 = 3 |
% |
Modulo | 7 % 2 = 1 |
** |
Exponentiation | 2 ** 3 = 8 |
True division (/) always returns a float, even for integers: 6 / 3 gives 2.0.
Floor division (//) rounds toward negative infinity: -7 // 2 gives -4, not -3.
Modulo (%) follows the sign of the divisor in Python: -7 % 2 gives 1 (not -1 as in C).
Type promotion: int op float gives float; int op complex gives complex.
Operators also work on non-numeric types: + concatenates strings/lists, * repeats sequences.
/ always returns float: 6 / 3 = 2.0
// floors toward negative infinity: -7 // 2 = -4
% follows divisor's sign: -7 % 2 = 1
** is exponentiation: 2 ** 3 = 8
Invariant: a == (a // b) * b + (a % b)
# Basic arithmetic
print(5 + 3) # 8
print(5 - 3) # 2
print(5 * 3) # 15
print(7 / 2) # 3.5 (true division, always float)
print(6 / 3) # 2.0 (still float!)
print(7 // 2) # 3 (floor division)
print(7 % 2) # 1 (modulo)
print(2 ** 10) # 1024 (exponentiation)
# Floor division rounds toward negative infinity
print(7 // 2) # 3
print(-7 // 2) # -4 (not -3!)
print(7.5 // 2) # 3.0 (floor div with float gives float)
# Modulo follows the divisor's sign
print(7 % 3) # 1
print(-7 % 3) # 2 (not -1!)
print(7 % -3) # -2
# The invariant always holds: a == (a // b) * b + (a % b)
a, b = -7, 2
print(a == (a // b) * b + (a % b)) # True
# Type promotion
print(type(5 + 3.0)) # <class 'float'>
print(type(5 + 3j)) # <class 'complex'>
# Operators on non-numeric types
print("hello" + " world") # 'hello world'
print("ha" * 3) # 'hahaha'
print([1, 2] + [3, 4]) # [1, 2, 3, 4]
print([0] * 5) # [0, 0, 0, 0, 0]
- •/ always returns float, even for exact integer division
- •// floors toward negative infinity, not toward zero
- •% follows the divisor's sign, unlike C
- •The invariant a == (a // b) * b + (a % b) always holds
- •+ concatenates sequences, * repeats them
- •-7 // 2 is -4 (floor), not -3 (truncation) -- different from C/Java
- •-7 % 2 is 1 in Python, but -1 in C/Java
- •6 / 3 gives 2.0, not 2 -- use // for integer result
- •[0] * 3 creates [0, 0, 0] with shared references -- fine for immutables, dangerous for mutables: [[]] * 3 shares the same inner list