Explain it simply
Explain it simply
Python stores numbers in three main types. An int is a whole number like 10, -5 or 1000; a float has a decimal point, like 3.14 or -0.5; and a complex number such as 2 + 3j is used in maths and engineering. Python picks the type from the way you write the value: a decimal point makes it a float, no decimal point makes it an int.
The type matters because the same operator can give different results depending on it: 7 / 2 gives 3.5 (a float), while 7 // 2 gives 3 (an int). This lesson shows which operator returns which type, and why floats are not always exact.
Problem → Why → Solution
The problem: the prices add up, yet == says False
A shop gives a free gift when two items priced 1.10 and 2.20 add up to exactly 3.30. The numbers are correct on paper, yet the program never hands out the gift. There is no error message: the if condition is simply False. Only when you print the total do you see 3.3000000000000003.
item_a = 1.10
item_b = 2.20
total = item_a + item_b
if total == 3.30:
print("Free gift!")
else:
print("No gift") # this branch runs
print(total) # 3.3000000000000003Why does this happen?
Computers store floats in binary (base 2). Just as 1/3 needs endless digits in decimal (0.333...), values such as 0.1, 1.1 and 2.2 cannot be written exactly in binary, so the nearest possible value is stored. Those tiny errors add up, and == checks for an exact match, so it returns False. This is not a Python bug; every language that uses IEEE 754 floats behaves the same way.
Core concept: three number types and the arithmetic operators
A Python int has no size limit. Even a huge value such as 2 ** 100 is stored with every digit exact, and an int can grow as large as memory allows. You can write long numbers with underscores, like 1_000_000, to keep them readable. A float uses the 64-bit IEEE 754 format, so it carries only about 15-17 significant digits and stores most decimal values, such as 0.1, as the nearest binary approximation.
| Operator | Meaning | With 7 and 2 |
|---|---|---|
| + | Addition | 7 + 2 → 9 |
| - | Subtraction | 7 - 2 → 5 |
| * | Multiplication | 7 * 2 → 14 |
| / | True division, always returns a float | 7 / 2 → 3.5 |
| // | Floor division, rounds down | 7 // 2 → 3 |
| % | Remainder (modulus) | 7 % 2 → 1 |
| ** | Power (exponentiation) | 7 ** 2 → 49 |
/ always returns a float, even when both operands are ints: 10 / 2 is 5.0, not 5. Use // when you want a whole-number result. // does not round to the nearest integer; it rounds down (the floor), so -7 // 2 is -4, not -3. % is defined to match that floor, and its result takes the sign of the divisor, so -7 % 2 is 1. The identity (a // b) * b + a % b == a always holds.
When you mix types, Python widens the result to the broader type: int plus float gives a float, and float plus complex gives a complex. Built-ins such as abs(), pow() and round() need no import, and the math module adds sqrt(), floor(), ceil() and isclose(). Where you need exact decimal arithmetic, as with money, use decimal.Decimal; for exact ratios like 1/3, use fractions.Fraction.
To see a value's type, call type(value); to branch on the type inside your code, use isinstance(value, float). Large or tiny floats can also be written in scientific notation, such as 1e3 for 1000.0, and the e alone is enough to make the literal a float.
- Literal sets the type (10 is int)
- Mixed types widen to float
- / gives float; // and % floor
- Never compare float results with ==
An int is exact and a float is an approximation; when exactness matters, choose int or Decimal.
General pattern
whole = 42 # int
real = 3.5 # float
cplx = 2 + 3j # complex
quotient = a / b # always float
floored = a // b # rounded down
remainder = a % b # what is left over
power = base ** exponent
value = round(number, ndigits)The decimal point decides the type, and each operator produces a different kind of result. round()'s second argument is the number of decimal places; leave it out and you get an int back.
Example: number types, operators and float precision
This example creates one value of each type and shows it with type(). It then runs all seven operators on 7 and 3, tries conversions and a few built-ins, and finishes by reproducing the float precision surprise from the problem section.
# ===== 1. Number Types =====
x = 10 # int
y = 3.14 # float
z = 2 + 3j # complex
print(f"Int: {x}, Type: {type(x)}")
print(f"Float: {y}, Type: {type(y)}")
print(f"Complex: {z}, Type: {type(z)}")
# ===== 2. Arithmetic Operations =====
a = 7
b = 3
print("\n===== Arithmetic Operators =====")
print(f"{a} + {b} = {a + b}") # Addition
print(f"{a} - {b} = {a - b}") # Subtraction
print(f"{a} * {b} = {a * b}") # Multiplication
print(f"{a} / {b} = {a / b}") # Division (always a float)
print(f"{a} // {b} = {a // b}") # Floor Division
print(f"{a} % {b} = {a % b}") # Modulus (remainder)
print(f"{a} ** {b} = {a ** b}") # Exponentiation
# ===== 3. Type Conversion =====
print("\n===== Type Conversion =====")
num = 5
print(f"int to float: {float(num)}") # 5.0
print(f"float to int: {int(3.99)}") # 3 (cuts off, does not round)
# ===== 4. Useful Functions =====
print("\n===== Useful Functions =====")
print(f"abs(-10) = {abs(-10)}") # Absolute value
print(f"pow(2, 4) = {pow(2, 4)}") # Power
print(f"round(3.14159, 2) = {round(3.14159, 2)}") # Rounding
# ===== 5. Float Precision =====
print("\n===== Float Precision =====")
print(f"0.1 + 0.2 = {0.1 + 0.2}")
print(f"0.1 + 0.2 == 0.3 -> {0.1 + 0.2 == 0.3}")Code breakdown
- Line 4
z = 2 + 3j # complexPython writes the imaginary part with j (maths uses i). type(z) prints <class 'complex'>.
- Line 18
print(f"{a} / {b} = {a / b}") # Division (always a float)7 / 3 prints 2.3333333333333335; the trailing 5 is the float approximation showing through.
- Lines 19-20
print(f"{a} // {b} = {a // b}") # Floor Division7 // 3 is 2 and 7 % 3 is 1. Since 3 * 2 + 1 is 7 again, // and % always work as a pair.
- Line 27
print(f"float to int: {int(3.99)}") # 3 (cuts off, does not round)int() cuts off everything after the decimal point instead of rounding, which is why 3.99 becomes 3, not 4.
- Line 38
print(f"0.1 + 0.2 == 0.3 -> {0.1 + 0.2 == 0.3}")The sum is 0.30000000000000004, so == returns False. Compare floats with math.isclose() instead.
Int: 10, Type: <class 'int'>
Float: 3.14, Type: <class 'float'>
Complex: (2+3j), Type: <class 'complex'>
===== Arithmetic Operators =====
7 + 3 = 10
7 - 3 = 4
7 * 3 = 21
7 / 3 = 2.3333333333333335
7 // 3 = 2
7 % 3 = 1
7 ** 3 = 343
===== Type Conversion =====
int to float: 5.0
float to int: 3
===== Useful Functions =====
abs(-10) = 10
pow(2, 4) = 16
round(3.14159, 2) = 3.14
===== Float Precision =====
0.1 + 0.2 = 0.30000000000000004
0.1 + 0.2 == 0.3 -> FalseRounding and Decimal
round() does not use the "5 always rounds up" rule from school. An exact half rounds to the nearest even number (banker's rounding): round(2.5) is 2 and round(3.5) is 4. On top of that, the float 2.675 is really stored as 2.67499999..., so round(2.675, 2) gives 2.67, not 2.68.
A Decimal built from a string keeps exactly the digits you wrote, and quantize() lets you choose the rounding rule yourself. Building one from a float, as in Decimal(0.1), copies the float's error too, so always pass a string.
from decimal import Decimal, ROUND_HALF_UP
print(round(2.5), round(3.5)) # 2 4 (halves go to even)
print(round(2.675, 2)) # 2.67 (the float is slightly below 2.675)
price = Decimal("2.675")
print(price.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)) # 2.68
print(Decimal("0.1") + Decimal("0.2") == Decimal("0.3")) # TrueIn real projects
Where this shows up in real projects
E-commerce and banking systems do not store money as floats. They use one of two approaches: keep $19.99 as 1999 cents in an int and divide by 100 only for display, or calculate with Decimal and store the value in a DECIMAL/NUMERIC database column. When a bill is split between people, // gives each share and % gives the cents left over.
% turns up in everyday code more often than you might expect: n % 2 == 0 tests for an even number, index % len(items) wraps around a list, and seconds // 60 with seconds % 60 splits a duration into minutes and seconds. In science and data analysis, floats are the default because they are fast and precise enough, and results are compared with math.isclose() or an explicit tolerance.
Common mistakes
Common mistakes
1. Testing a float result with ==
A condition like if total == 3.30: cannot be trusted for a calculated float. Use math.isclose(total, 3.30), or for money calculate in int cents so the comparison becomes int against int, such as 330 == 330.
2. Expecting / to return an int
items[len(items) / 2] raises TypeError: list indices must be integers or slices, not float, because / returns 2.0 even for 4 / 2. Use // whenever you need an index or a count.
3. Assuming int() rounds
int(2.9) is 2, not 3, and int(-2.9) is -2: it truncates toward zero. Use round() for the nearest whole number, or math.floor() when you always want to round down.
Best practices
Best practices
- Store money as int cents or as a Decimal created from a string.
- Compare floats with math.isclose().
- When you only need rounding for display, format with f"{value:.2f}" and leave the stored value untouched.
- Write long literals with underscores, such as 1_000_000.
Mini challenge
Mini challenge: a bill-splitting helper
Write a function that splits 100.00 between three people and another that rounds money to two decimal places. Also print how a float total and a Decimal total differ.
- split_bill(total_cents, people) returns a (cents each, cents left over) tuple using // and %
- to_money(amount) turns a string into a Decimal rounded to 2 places with ROUND_HALF_UP
- Add 0.10 ten times as a float and as a Decimal, then print both totals
- Check the float total with == 1.0 and with math.isclose()
import math
from decimal import Decimal, ROUND_HALF_UP
def split_bill(total_cents: int, people: int) -> tuple[int, int]:
# TODO: return (cents each person pays, cents left over)
...
def to_money(amount: str) -> Decimal:
# TODO: Decimal(amount) rounded to 0.01 with ROUND_HALF_UP
...
# TODO: split 10_000 cents between 3 people and print the share
# TODO: add 0.10 ten times as float and as Decimal, print both totals
# TODO: compare the float total with == 1.0 and with math.isclose()
# TODO: print round(2.675, 2) next to to_money("2.675")Expected: The program prints: Each pays 33.33, 1 cent(s) left over Float total: 0.9999999999999999 Decimal total: 1.00 Float total == 1.0 -> False isclose(float_total, 1.0) -> True round(2.675, 2) = 2.67 to_money('2.675') = 2.68
Show hint
Decimal(amount).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) rounds to two places. Accumulate with += in a loop: since Python 3.12, sum() adds floats more precisely, which would hide the error you want to see.
Show solution
import math
from decimal import Decimal, ROUND_HALF_UP
def split_bill(total_cents: int, people: int) -> tuple[int, int]:
"""Return (cents each person pays, cents left over)."""
return total_cents // people, total_cents % people
def to_money(amount: str) -> Decimal:
"""Round a decimal string to 2 places; halves round up."""
return Decimal(amount).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
each, left = split_bill(10_000, 3)
print(f"Each pays {each / 100:.2f}, {left} cent(s) left over")
float_total = 0.0
decimal_total = Decimal("0")
for _ in range(10):
float_total += 0.10
decimal_total += Decimal("0.10")
print(f"Float total: {float_total}")
print(f"Decimal total: {decimal_total}")
print(f"Float total == 1.0 -> {float_total == 1.0}")
print(f"isclose(float_total, 1.0) -> {math.isclose(float_total, 1.0)}")
print(f"round(2.675, 2) = {round(2.675, 2)}")
print(f"to_money('2.675') = {to_money('2.675')}")Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- int is exact with no size limit; float is a binary approximation.
- / always returns a float, // and % are based on the floor, and ** raises to a power.
- Compare float results with math.isclose(), not ==.
- For money, use int cents or a Decimal created from a string.
The Python Tutorial — Python Software Foundation