Programming

Operators and expressions

Arithmetic, comparison and logical operators, and precedence.

All lessons · Python lessons: learn from scratch

Arithmetic operators

Python's basic arithmetic uses + - * /. Three more are handy: // for whole-number division, % for the remainder and ** for powers.

print(17 / 5)    # 3.4
print(17 // 5)   # 3
print(17 % 5)    # 2
print(2 ** 10)   # 1024

The remainder operator is often used to test evenness: if n % 2 == 0, then n is even. The / operator always returns a float, even when the result is whole.

Comparison and logic

Comparison operators == != < > <= >= return a bool. Combine them with and, or, not. Watch out: testing equality needs two equals signs (==).

age = 20
has_ticket = True
print(age >= 18 and has_ticket)   # True
print(not has_ticket)              # False
print(1 < age < 30)                # True (chained)

Order of evaluation

Python follows mathematical precedence: ** first, then * / // %, then + -, then comparisons, then not, and, or. When in doubt use parentheses; they make code both correct and readable.

print(2 + 3 * 4)      # 14
print((2 + 3) * 4)    # 20
print(-3 ** 2)        # -9
print((-3) ** 2)      # 9
  • x += 5 is shorthand for x = x + 5.
  • The same shorthand exists for -=, *= and /=.

Author: Nibras Code