Kahibaro
Discord Login Register

Working with numbers

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:

Integer vs Float: What Actually Happens

Python has (at least) two basic numeric types you will use all the time:

Python usually decides which type to use based on how you write the number:

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:

Division: `/` vs `//`

Python has two main division operators:

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.0

Floor division `//`

// divides and then rounds down to the nearest whole number:

print(7 // 2)     # 3
print(7.0 // 2)   # 3.0
print(-7 // 2)    # -4

Notice the negative example:

Use // when:

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)  # 4

Remainders with `%`

The modulo operator % gives you the remainder after division.

print(7 % 3)     # 1
print(10 % 2)    # 0
print(23 % 5)    # 3

Common uses:

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.

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:

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.

print(int(3.9))     # 3
print(int(-3.9))    # -3 (toward zero)
print(float(3))     # 3.0

Converting 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)  # 19

This is useful when:

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)        # 4

From int to float

Use float() when you want decimal behavior:

count = 5
count_float = float(count)
print(count_float)   # 5.0

This is often useful when:

Example:

items = 3
total_weight = 2.7  # kilograms
average = total_weight / float(items)
print(average)  # 0.9

Useful 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.2

Use it when:

`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))  # 9

You 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():

print(2 ** 3)        # 8
print(pow(2, 3))     # 8

A 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.1

Floating‑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.30000000000000004

This is not a bug in Python; it’s how most computers represent decimal numbers internally.

What you need to remember:

Example with rounding:

value = 0.1 + 0.2
print(value)              # 0.30000000000000004
print(round(value, 2))    # 0.3

A 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 - 2

You 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.0

Practical 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)   # 10

Example 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.

Views: 15

Comments

Please login to add a comment.

Don't have an account? Register now!