KAHIBARO Bookshelves
Discord Login Register

4.2. 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:

  • 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, 42
  • float — floating‑point numbers (numbers with a decimal point), like 3.14, 0.0, -2.5

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

  • 10 → int
  • 10.0 → float
  • 0.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 float in an arithmetic expression (like +, -, *, /), the result will usually be a float.

Division: `/` vs `//`

Python has two main division operators:

  • / — true division (always gives a float)
  • // — 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.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:

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

Remainders with `%`

The modulo operator % gives you the remainder after division.

  • $7 \div 3 = 2$ remainder $1$
  • So 7 % 3 is 1
print(7 % 3)     # 1
print(10 % 2)    # 0
print(23 % 5)    # 3

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

  • digits is optional
  • If digits is 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:

  • float if you specify digits
  • int if you don’t specify digits and 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.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:

  • 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)        # 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:

  • 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.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:

  • 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))  # 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():

  • a ** b → $a^b$
  • pow(a, b) → the same as a ** b
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.

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

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms