guidebeginner12 min
Operators and Math
Arithmetic, comparison, and logical operators—the tools for calculations and decisions.
Prerequisites
Last updated: Jan 28, 2026
Operators are symbols that tell Python to perform specific operations. You've already seen some: + for addition, = for assignment. Let's look at all of them.
Arithmetic Operators
python
# Basic math
print(10 + 3) # 13 Addition
print(10 - 3) # 7 Subtraction
print(10 * 3) # 30 Multiplication
print(10 / 3) # 3.333... Division (always returns float)
# More operations
print(10 // 3) # 3 Integer division (rounds down)
print(10 % 3) # 1 Modulo (remainder after division)
print(10 ** 3) # 1000 Exponentiation (10 to the power of 3)Order of Operations
Python follows standard math rules (PEMDAS):
python
# Parentheses first, then exponents, then multiply/divide, then add/subtract
print(2 + 3 * 4) # 14, not 20 (multiplication first)
print((2 + 3) * 4) # 20 (parentheses first)
print(2 ** 3 ** 2) # 512 (exponents right to left: 3**2=9, then 2**9=512)
print(10 - 5 - 2) # 3 (left to right for same precedence)
# When in doubt, use parentheses
total = (price * quantity) + tax # Clear intentionAssignment Shortcuts
Python has shortcuts for modifying variables:
python
score = 100
score = score + 10 # Long way
score += 10 # Short way (same result)
# All arithmetic operators have shortcuts
x = 20
x -= 5 # x = x - 5 → 15
x *= 2 # x = x * 2 → 30
x /= 3 # x = x / 3 → 10.0
x //= 2 # x = x // 2 → 5.0
x **= 2 # x = x ** 2 → 25.0Comparison Operators
These compare values and return True or False:
python
a = 10
b = 5
print(a == b) # False Equal to
print(a != b) # True Not equal to
print(a > b) # True Greater than
print(a < b) # False Less than
print(a >= b) # True Greater than or equal
print(a <= b) # False Less than or equalLogical Operators
Combine multiple conditions with and, or, not:
python
age = 25
has_license = True
# and: Both must be True
can_drive = age >= 16 and has_license
print(can_drive) # True
# or: At least one must be True
is_weekend = False
is_holiday = True
day_off = is_weekend or is_holiday
print(day_off) # True
# not: Flips True to False and vice versa
is_working = not day_off
print(is_working) # FalseChaining Comparisons
Python lets you chain comparisons naturally:
python
age = 25
# Instead of: age >= 18 and age <= 65
print(18 <= age <= 65) # True
x = 5
print(1 < x < 10) # True (x is between 1 and 10)Practice Problems
- Calculate the average of three test scores
- Convert a temperature from Celsius to Fahrenheit (F = C * 9/5 + 32)
- Check if a number is even (hint: use %)
- Check if a year is a leap year (divisible by 4, except centuries unless divisible by 400)
- Calculate compound interest: final = principal * (1 + rate) ** years