Arithmetic operators work the way you’d expect from school maths. We already touched on them in Section 2 — this lesson covers the full set.

The seven operators

a: int = 10
b: int = 3

print(a + b)    # 13   addition
print(a - b)    # 7    subtraction
print(a * b)    # 30   multiplication
print(a / b)    # 3.333...   true division (always float)
print(a // b)   # 3    floor division (drops the remainder)
print(a % b)    # 1    modulo (remainder)
print(a ** b)   # 1000 exponent (a to the power b)

Two of these tend to trip newcomers:

  • / always returns a float, even when both sides are integers. 6 / 2 is 3.0, not 3.
  • // does integer-style division, rounding toward negative infinity. 7 // 2 is 3. But -7 // 2 is -4, not -3.

Modulo is more useful than it looks

The % operator gives the remainder after division. It comes up surprisingly often:

# Is a number even or odd?
n: int = 14
print(n % 2 == 0)   # True → even

# Cycle through values 0, 1, 2, 0, 1, 2, ...
for i in range(10):
    print(i % 3, end=" ")
0 1 2 0 1 2 0 1 2 0

You’ll see modulo in everything from training-loop bookkeeping to cycling through colours.

Exponent

a ** b is a to the power of b:

print(2 ** 10)     # 1024
print(5 ** 2)      # 25
print(2 ** 0.5)    # 1.4142... → square root of 2
print(9 ** 0.5)    # 3.0       → square root of 9

A fractional exponent gives a root. x ** 0.5 is the same as math.sqrt(x).

Operator precedence

When multiple operators appear in one expression, Python follows the same order you learned in maths class — ** first, then * / // %, then + -:

print(2 + 3 * 4)       # 14, not 20
print(2 ** 3 ** 2)     # 512, because ** is right-to-left: 2 ** (3 ** 2) = 2 ** 9
print((2 + 3) * 4)     # 20 — parentheses force the order

When in doubt, add parentheses. They cost nothing and make code easier to read.

Negative numbers

The - sign in front of a number is also an operator (called the unary minus):

x: int = 5
y: int = -x         # -5
z: int = -(-x)      # 5

Mixing int and float

When you mix an int and a float, the result is always a float:

print(3 + 0.5)     # 3.5  — int + float → float
print(10 / 2)      # 5.0  — / always returns float
print(10 // 2)     # 5    — // stays int when both inputs are int
print(10 // 2.0)   # 5.0  — but becomes float if either side is float

A maths-class quick check

# average of three numbers
a: float = 4.0
b: float = 7.5
c: float = 9.5
average: float = (a + b + c) / 3
print(average)   # 7.0

# distance between two points
import math

x1, y1 = 0.0, 0.0
x2, y2 = 3.0, 4.0
distance: float = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
print(distance)   # 5.0

We’ll cover importing modules properly in Section 11. For now, just know that math.sqrt lives in the math module that comes with Python.

What’s next

You can do maths. Next, we’ll compare values — the comparison operators that produce booleans.

Toggle theme (T)