Chapter 2

Numbers and Operators

Use Python as a calculator with arithmetic, comparison and shorthand operators.

Python can work as a powerful calculator. It supports the usual arithmetic plus a few handy operators for whole-number maths.

Arithmetic operators

  • + addition, - subtraction, * multiplication.
  • / true division — always gives a float, so 6 / 2 is 3.0.
  • // floor division — divides then drops the fraction, so 7 // 2 is 3.
  • % modulo — the remainder, so 7 % 2 is 1.
  • ** power, so 2 ** 3 is 8.
print(6 / 2)    # 3.0
print(7 // 2)   # 3
print(7 % 2)    # 1
print(2 ** 3)   # 8

Order of operations

Python follows normal maths rules: brackets first, then power, then multiply and divide, then add and subtract. Use round brackets to be clear:

print(2 + 3 * 4)      # 14
print((2 + 3) * 4)    # 20

Comparison operators

These compare two values and give a bool:

  • == equal to, != not equal to.
  • < less than, > greater than.
  • <= less than or equal, >= greater than or equal.
print(5 == 5)   # True
print(5 != 3)   # True
print(4 <= 4)   # True

Shorthand assignment

Operators can combine with assignment to update a variable:

score = 10
score += 5   # same as score = score + 5, now 15
score -= 2   # now 13

The same idea works with *=, /= and others. These save you from writing the variable name twice.

Mixing integers and floats

When you combine an int with a float, the answer becomes a float:

print(3 + 1.0)   # 4.0
print(10 * 2.5)  # 25.0

This is why measurements and money are often kept as floats.

Rounding and helpers

Python has built-in helpers for common maths:

  • round(x) rounds to the nearest whole number, so round(3.6) is 4.
  • abs(x) gives the size without a sign, so abs(-7) is 7.
  • round(x, 2) keeps two decimal places.
print(round(3.14159, 2))   # 3.14
print(abs(-5))             # 5

Chained comparisons

Python lets you write natural range checks in one go:

x = 5
print(1 < x < 10)   # True

Remember

  • A single slash always gives a float; use // when you want a whole number.
  • % gives the remainder — useful for testing if a number is even.
  • Use == to compare and = to assign; mixing them is a common mistake.

Stuck on this topic? A verified JomKelas tutor can walk you through it.

Find a verified tutor