Table of Contents
Understanding How Python Handles Numbers
You have already seen basic arithmetic operators. In this chapter, you will focus on how to work with numbers in Python: how they behave, how they are stored, and how to use them in common situations.
This chapter covers:
- Different numeric types and how they behave in operations
- Integer vs float division
- Rounding numbers
- Converting between numeric types
- Useful built-in functions for numbers
- The idea of floating‑point precision (why some decimals look “weird”)
Integer vs Float: What Actually Happens
Python has (at least) two basic numeric types you will use all the time:
int— integers (whole numbers), like-3,0,42float— floating‑point numbers (numbers with a decimal point), like3.14,0.0,-2.5
Python usually decides which type to use based on how you write the number:
10→int10.0→float0.5→float
You can check the type with type():
x = 10
y = 10.0
print(type(x)) # <class 'int'>
print(type(y)) # <class 'float'>Mixing ints and floats in expressions
When you combine an int and a float in the same operation, Python automatically converts the int to a float so the result can hold decimals:
a = 5 # int
b = 2.0 # float
result = a + b
print(result) # 7.0
print(type(result)) # <class 'float'>This automatic conversion is called type promotion. The rule you need:
- If there is any
floatin an arithmetic expression (like+,-,*,/), the result will usually be afloat.
Division: `/` vs `//`
Python has two main division operators:
/— true division (always gives afloat)//— floor division (division with result rounded down)
True division `/`
/ always returns a float, even if the division is “even”:
print(10 / 2) # 5.0 (float)
print(7 / 2) # 3.5
print(3 / 1) # 3.0Floor division `//`
// divides and then rounds down to the nearest whole number:
print(7 // 2) # 3
print(7.0 // 2) # 3.0
print(-7 // 2) # -4Notice the negative example:
- $-7 \div 2 = -3.5$, but floor division goes “down” to the smaller number: $-4$
Use // when:
- You want “how many whole times does this fit?”
- You’re working with things like page numbers, rows, or chunks.
Example: how many full boxes of 5 apples can you make from 23 apples?
apples = 23
box_size = 5
full_boxes = apples // box_size
print(full_boxes) # 4Remainders with `%`
The modulo operator % gives you the remainder after division.
- $7 \div 3 = 2$ remainder $1$
- So
7 % 3is1
print(7 % 3) # 1
print(10 % 2) # 0
print(23 % 5) # 3Common uses:
- Check if a number is even: “no remainder when dividing by 2”
- Work with repeating patterns (e.g., days of the week, positions in a circle)
number = 14
if number % 2 == 0:
print("Even")
else:
print("Odd")Rounding Numbers
When you work with float values, you often want to round them. Python gives you several ways.
The `round()` function
round(number, digits) rounds a number to a given number of decimal places.
digitsis optional- If
digitsis left out, Python rounds to the nearest whole number
print(round(3.14159, 2)) # 3.14
print(round(3.14159, 3)) # 3.142
print(round(3.5)) # 4
print(round(3.4)) # 3
Note: round() returns a:
floatif you specifydigitsintif you don’t specifydigitsand the result is a whole number
print(type(round(3.14159, 2))) # <class 'float'>
print(type(round(3.5))) # <class 'int'>`int()` and `float()` for simple conversions
int() and float() can also be used to force simple kinds of rounding/conversion.
int(number)removes the decimal part (it does not round, it just truncates toward zero)float(number)converts to a float
print(int(3.9)) # 3
print(int(-3.9)) # -3 (toward zero)
print(float(3)) # 3.0Converting Between Numeric Types
Sometimes you need a specific numeric type for an operation or to display something nicely.
From float to int
Use int() when you are sure you want to lose the decimal part:
price = 19.99
price_whole = int(price)
print(price_whole) # 19This is useful when:
- You want an index for a list (covered later)
- You only care about the whole number part
If you actually need rounded values, combine round() and int() carefully:
number = 3.6
rounded = round(number) # 4
rounded_int = int(rounded)
print(rounded_int) # 4From int to float
Use float() when you want decimal behavior:
count = 5
count_float = float(count)
print(count_float) # 5.0This is often useful when:
- You want division to give you decimal results
- You’re mixing counts with measurements
Example:
items = 3
total_weight = 2.7 # kilograms
average = total_weight / float(items)
print(average) # 0.9Useful Built‑in Functions for Numbers
Python has several built‑in functions that work nicely with numbers.
`abs()` — absolute value
abs(x) returns the distance from zero (always non‑negative):
print(abs(5)) # 5
print(abs(-5)) # 5
print(abs(-3.2)) # 3.2Use it when:
- You only care about “how big” a difference is, not its direction
- You want to measure error or distance
`min()` and `max()`
min() and max() find the smallest and largest values:
a = 5
b = 2
c = 9
print(min(a, b, c)) # 2
print(max(a, b, c)) # 9You can also use them with lists (covered later):
numbers = [3, 7, 1, 9]
print(min(numbers)) # 1
print(max(numbers)) # 9`pow()` and `**` (exponentiation)
You already know ** from basic arithmetic. There is also a function pow():
a ** b→ $a^b$pow(a, b)→ the same asa ** b
print(2 ** 3) # 8
print(pow(2, 3)) # 8A practical example: compound growth
If something grows by $r$ percent each time, after $n$ steps:
$$
\text{final} = \text{start} \times (1 + r)^n
$$
In Python:
start = 100
rate = 0.10 # 10%
years = 3
final = start * (1 + rate) ** years
print(final) # 133.1Floating‑Point Precision: Why 0.1 + 0.2 Is Weird
When you work with decimals in Python, you might sometimes see results like this:
print(0.1 + 0.2) # 0.30000000000000004This is not a bug in Python; it’s how most computers represent decimal numbers internally.
- Many decimal fractions (like $0.1$ or $0.2$) cannot be represented exactly in binary.
- The computer picks the closest possible value, which sometimes leads to tiny rounding errors.
What you need to remember:
- Don’t rely on floats to be exact when comparing for equality.
- If you need to display results, use rounding or formatting (output formatting is covered later).
Example with rounding:
value = 0.1 + 0.2
print(value) # 0.30000000000000004
print(round(value, 2)) # 0.3A safer way to compare floats is to check if they are “close enough,” not exactly equal. A simple idea:
$$
|a - b| < \epsilon
$$
Where $\epsilon$ is a small number like $0.000001$.
Basic example:
a = 0.1 + 0.2
b = 0.3
epsilon = 0.000001
are_close = abs(a - b) < epsilon
print(are_close) # True(For real‑world work, there are more precise tools, but this idea is enough for now.)
Incrementing and Decrementing Numbers
You will often want to “add 1” or “subtract 1” from a number, especially in loops.
Python does not have ++ or -- like some other languages. Instead, you write:
count = 0
count = count + 1 # increment by 1
count = count - 1 # decrement by 1
A shorter form uses += and -=:
count = 0
count += 1 # same as count = count + 1
count += 5 # same as count = count + 5
count -= 2 # same as count = count - 2You can also use these with other operators:
x = 10
x *= 2 # x = x * 2 -> 20
x /= 4 # x = x / 4 -> 5.0
x //= 2 # x = x // 2 -> 2.0Practical Mini‑Examples
Here are a few small examples that combine what you’ve seen in this chapter.
Example 1: Average of three test scores
score1 = 78
score2 = 85
score3 = 92
total = score1 + score2 + score3
average = total / 3
print("Raw average:", average)
print("Rounded average:", round(average, 1))Example 2: Time conversion (minutes to hours and minutes)
total_minutes = 130
hours = total_minutes // 60 # whole hours
minutes = total_minutes % 60 # leftover minutes
print("Hours:", hours) # 2
print("Minutes:", minutes) # 10Example 3: Discount calculation
price = 59.99
discount_percent = 20 # 20%
discount = price * discount_percent / 100
final_price = price - discount
print("Discount:", round(discount, 2))
print("Final price:", round(final_price, 2))These kinds of small calculations are the foundation of many real programs: budgets, scores, measurements, timers, and much more. In later chapters, you will combine numeric operations with conditions, loops, and data collections to build more complex and useful programs.