Skip to content
elephantoo

Numbers & operators

Lesson 3 of 38 12 min read

int and float, arithmetic and division gotchas, precedence, comparisons, math and Decimal for money.


Numbers are everywhere: prices, scores, sensor readings, pixel coordinates. Python has two everyday numeric types — int and float — plus a rich set of operators and a few precise tools for when "close enough" isn't good enough.

Integers and floats#

Python
students = 120          # int: whole number
price = 499.99          # float: has a decimal point
population = 1_428_627_663   # underscores make big numbers readable
tiny = 2.5e-4           # scientific notation = 0.00025
huge = 2 ** 100         # ints never overflow in Python

print(population)
print(tiny)
print(huge)
Output
1428627663
0.00025
1267650600228229401496703205376

Unlike Java or C, Python's int grows as large as memory allows, so you never need to worry about overflow with whole numbers.

Mixing types is fine: an int combined with a float gives a float.

Python
print(3 + 2.0)
print(type(3 + 2.0))
Output
5.0
<class 'float'>

Arithmetic operators#

OperatorMeaningExampleResult
+addition7 + 29
-subtraction7 - 25
*multiplication7 * 214
/true division (always float)7 / 23.5
//floor division7 // 23
%remainder (modulo)7 % 21
**power7 ** 249

The two division operators are the classic gotcha:

Python
print(10 / 2)     # true division ALWAYS returns a float
print(10 // 3)    # floor division rounds down
print(-7 // 2)    # "down" means toward negative infinity
print(10 % 3)     # remainder
print(divmod(17, 5))  # quotient and remainder together
Output
5.0
3
-4
1
(3, 2)

% is handy for "every Nth item" and "is it even?" checks:

Python
for n in range(1, 7):
    if n % 2 == 0:
        print(n, "is even")
Output
2 is even
4 is even
6 is even

Operator precedence#

Python follows the usual maths rules: ** first, then * / // %, then + -. Use parentheses to make intent obvious:

Python
print(2 + 3 * 4)       # 14, not 20
print((2 + 3) * 4)     # 20
print(-3 ** 2)         # -9: ** binds tighter than unary minus
print(2 ** 3 ** 2)     # 512: ** groups right-to-left
Output
14
20
-9
512

Augmented assignment#

Updating a variable based on its current value is so common that there's a shortcut for every operator:

Python
score = 10
score += 5     # score = score + 5
score *= 2     # score = score * 2
score -= 1
score //= 4
print(score)
Output
7

Python has no ++ or --; write count += 1.

Comparison and boolean operators#

Comparisons produce True or False, and can be chained just like in maths:

Python
age = 25
print(age >= 18)
print(18 <= age < 65)          # chained comparison
print(age == 25 and age != 30)
print(age < 18 or age > 60)
print(not age > 30)
Output
True
True
True
False
True

and and or short-circuit: and stops at the first falsy value, or stops at the first truthy one. They also return one of their operands, which enables a common default-value idiom:

Python
name = ""
display = name or "Anonymous"
print(display)
Output
Anonymous

Useful built-in functions and the math module#

Python
import math

print(abs(-8))              # absolute value
print(round(3.14159, 2))    # round to 2 decimal places
print(min(4, 9, 1), max(4, 9, 1))
print(sum([10, 20, 30]))
print(pow(2, 10))
print(math.sqrt(81))
print(math.floor(4.7), math.ceil(4.2))
print(math.pi)
Output
8
3.14
1 9
60
1024
9.0
4 5
3.141592653589793

Watch out: round() uses banker's rounding for exact halves — it rounds to the nearest even number. So round(2.5) is 2 and round(3.5) is 4.

The floating-point trap#

Floats are stored in binary, which can't represent most decimal fractions exactly. The result is tiny rounding errors:

Python
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
Output
0.30000000000000004
False

This isn't a Python bug — every language using IEEE 754 floats behaves this way. Two fixes:

Python
import math
from decimal import Decimal

# 1. Compare floats with a tolerance
print(math.isclose(0.1 + 0.2, 0.3))

# 2. Use Decimal when exact decimal arithmetic matters (money!)
total = Decimal("0.10") + Decimal("0.20")
print(total, total == Decimal("0.30"))
Output
True
0.30 True

Create Decimal values from strings, not floats — Decimal(0.1) faithfully copies the float's tiny error. Many financial apps simply store amounts as integer paise or cents instead.

Formatting numbers for humans#

You'll learn f-strings fully in the next lesson, but here's a taste of number formatting:

Python
revenue = 1234567.891
print(f"{revenue:,.2f}")     # thousands separator, 2 decimals
print(f"{0.256:.1%}")        # percentage
print(f"{42:05d}")           # zero-padded
Output
1,234,567.89
25.6%
00042

A worked example: splitting a bill#

Python
bill = 2450
tip_percent = 10
people = 4

tip = bill * tip_percent / 100
total = bill + tip
each = total / people

print(f"Tip: ₹{tip:.2f}")
print(f"Total: ₹{total:.2f}")
print(f"Each person pays: ₹{each:.2f}")
Output
Tip: ₹245.00
Total: ₹2695.00
Each person pays: ₹673.75

Common mistakes#

  • Expecting / to give an int. 10 / 2 is 5.0. Use // when you need a whole number.
  • Comparing floats with ==. Use math.isclose().
  • Forgetting that input() returns text. "5" * 2 is "55", not 10 — convert with int() first.
  • Using floats for money. Use Decimal or integer paise/cents.

What's next#

Numbers covered — now for text. Next lesson: strings and f-strings, the tools you'll use to build every message your program shows.

Check your understanding

Quick quiz

0/3 answered
  1. 1.What does 7 // 2 evaluate to in Python?

  2. 2.Why does 0.1 + 0.2 == 0.3 evaluate to False?

  3. 3.What is the value of 2 ** 3 ** 2?

Finished reading?

Mark this lesson complete to track your progress.