Work with Numbers
Master Python integers and floats in this hands-on tutorial. Learn core concepts, step-by-step operations, troubleshooting tips, and compare when to use each numeric type. Perfect for step-by-step learners.
Focus: work with numbers: integers and floats
Have you ever written code that looked right but produced a baffling result — like adding two numbers and getting a surprise decimal? That's the moment you realize Python treats whole numbers and fractions differently. Mastering integers and floats is the key to writing precise calculations, avoiding silent bugs, and building confidence in every script you write. This lesson gives you the mental model, step-by-step mechanics, and troubleshooting know-how to handle numbers like a pro.
The problem this lesson solves
Numbers are everywhere in code: counting items, calculating prices, measuring distances, or tracking time. But Python doesn't treat all numbers the same way. If you assume 10 / 3 gives 3 (like in some languages), you'll be surprised by 3.3333333333333335. If you compare 0.1 + 0.2 == 0.3, you might get False when you expected True. These aren't bugs — they're features of how Python stores integers (whole numbers) and floats (numbers with decimal points). Without knowing the difference, you'll waste hours debugging calculations that should just work.
Core concept / mental model
Think of an integer as a number you can count on your fingers: 0, 1, 42, -7. It's exact, unlimited in size (Python automatically handles huge values), and perfect for counting, indexing, and discrete math. A float (short for floating-point number) is like a measurement on a ruler: 3.14, -0.001, 2.0. Floats are approximations — they use a fixed number of bits to represent a wide range of values, which means some decimal numbers can't be stored exactly (e.g., 0.1 in binary).
Pro tip: Think of integers as "perfect" and floats as "good enough." Use integers when exactness matters (like loop counters or IDs). Use floats when fractions are okay (like measurements or percentages).
Definitions
- Integer (
int): A whole number, positive or negative, without a decimal point. Python'sintcan be arbitrarily large. - Float (
float): A number with a decimal point or an exponent, backed by the computer's floating-point hardware (usually 64-bit).
How it works step by step
Here's how Python decides whether a number is an integer or a float:
- Literal syntax: If you write
5, it's an integer. If you write5.0or5., it's a float. Scientific notation like1e3also produces a float (1000.0). - Type inference: Python assigns the type automatically based on the value. Use
type()to check. - Division always returns float: In Python 3, dividing two integers with
/always gives a float. Use//for integer (floor) division. - Mixed-type operations: When you combine an integer and a float in an arithmetic operation, Python converts the integer to a float first (this is called type coercion), and the result is a float.
- Conversion: You can manually convert between types using
int()andfloat().int()truncates toward zero;float()transforms an integer into its decimal equivalent.
Hands-on walkthrough
Let's see these concepts in action with three complete examples.
Example 1: Integer vs. float literals
# Integer literals
age = 30
temperature = -5
large_number = 2**100 # Python handles huge ints
# Float literals
pi = 3.14159
gravity = 9.8
scientific = 1.5e-3 # 0.0015
print(type(age)) # <class 'int'>
print(type(pi)) # <class 'float'>
print(type(scientific)) # <class 'float'>
print(large_number) # 1267650600228229401496703205376
Output:
<class 'int'>
<class 'float'>
<class 'float'>
1267650600228229401496703205376
Example 2: Operations and type coercion
a = 10
b = 3
# Division always returns float
result_div = a / b
print(f"10 / 3 = {result_div} (type: {type(result_div).__name__})")
# Integer (floor) division
result_floor = a // b
print(f"10 // 3 = {result_floor} (type: {type(result_floor).__name__})")
# Mixed type
c = 2.5
result_mixed = a + c
print(f"10 + 2.5 = {result_mixed} (type: {type(result_mixed).__name__})")
# Converting
x = int(3.9) # truncates to 3
y = float(7) # becomes 7.0
print(f"int(3.9) = {x}, float(7) = {y}")
Output:
10 / 3 = 3.3333333333333335 (type: float)
10 // 3 = 3 (type: int)
10 + 2.5 = 12.5 (type: float)
int(3.9) = 3, float(7) = 7.0
Example 3: The famous floating-point gotcha
# This is a classic example of float imprecision
result = 0.1 + 0.2
print(f"0.1 + 0.2 = {result}")
print(f"Is it equal to 0.3? {result == 0.3}")
# How to compare floats safely
epsilon = 1e-10
print(f"Close enough? {abs(result - 0.3) < epsilon}")
Output:
0.1 + 0.2 = 0.30000000000000004
Is it equal to 0.3? False
Close enough? True
Compare options / when to choose what
| Feature | Integer (int) |
Float (float) |
|---|---|---|
| Precision | Exact (arbitrary size) | Approximate (up to ~15-17 decimal digits) |
| Use case | Counters, indices, IDs, exact calculations | Measurements, percentages, scientific data |
| Memory | Variable (grows with size) | Fixed (8 bytes typical) |
| Division | // gives integer, / gives float |
All operations return float |
| Performance | Fast for small ints | Fast but limited by hardware |
When to choose what:
- Use integers for loop counters (for i in range(10)), indexing, counting items, and any financial or exact calculation (store currency as cents as an integer).
- Use floats for measurements, distances, percentages, and any situation where a decimal fraction is natural.
Variations
- Decimal module: For high-precision decimal arithmetic (e.g., financial calculations), use
from decimal import Decimal. It's slower but exact. - Fractions module: Use
from fractions import Fractionfor rational number arithmetic (like1/3 + 2/3). - Complex numbers: Python has a built-in
complextype for2+3j, used in scientific computing.
Troubleshooting & edge cases
Common mistake 1: Division returning a float
total_items = 10
people = 3
items_per_person = total_items / people # 3.333... not 3
print(int(items_per_person)) # 3 if you truncate
Fix: Use // for integer division if you need a whole number.
Common mistake 2: Float comparison failure
if 0.1 + 0.2 == 0.3:
print("Equal") # This never runs
Fix: Compare using a tolerance: abs((0.1 + 0.2) - 0.3) < 1e-10.
Common mistake 3: Silently losing precision with large integers
big_int = 10**30
big_float = float(big_int) # 1e+30 exactly? No
print(big_float == big_int) # False because float can't represent it exactly
Fix: Keep as integer for exactness; use Decimal if you need both range and precision.
Edge case: int() truncation vs. rounding
print(int(3.9)) # 3 (truncates toward zero)
print(int(-3.9)) # -3 (also truncates toward zero)
print(round(3.9)) # 4 (rounds to nearest even)
Note: int() always truncates toward zero; round() rounds to the nearest integer with ties going to even.
What you learned & what's next
You now understand:
- The difference between integers (exact whole numbers) and floats (approximate decimals)
- How division always returns a float, and how to get integer results with //
- How int() and float() convert between types
- The critical gotcha: floating-point precision and safe comparison
- When to choose each type for your code
What's next: Now that you can work with numbers, the next lesson shows you how to capture and use user input — so your programs aren't just static calculations, but interactive tools that respond to real people. You'll combine numbers with strings and input functions to build your first fully interactive script.
Practice recap
Try this: write a short script that asks the user for a temperature in Celsius (as a float) and prints it in Fahrenheit. Then modify it so it prints both the integer and float representations. Bonus: compare two calculated Fahrenheit values using both == and a tolerance to see the difference in action.
Common mistakes
- Expecting integer division: using
/instead of//to get a whole-number quotient, e.g.,5 / 2returns2.5instead of2. - Floating-point equality checks: comparing
0.1 + 0.2 == 0.3returnsFalsedue to binary representation limits; always use a tolerance likeabs(a - b) < 1e-10. - Accidentally converting large integers to float:
float(10**30)loses precision and may behave unexpectedly in comparisons. - Confusing
int()(truncates toward zero) withround()(rounds to nearest even) when converting floats to integers.
Variations
- Use the
decimal.Decimaltype for high-precision decimal arithmetic (e.g., currency calculations) when float imprecision is unacceptable. - Use the
fractions.Fractiontype for exact rational arithmetic (e.g.,Fraction(1,3) + Fraction(2,3)). - Use Python's built-in
complextype (2+3j) for scientific or engineering applications that need complex numbers.
Real-world use cases
- Calculating tax and discounts in an e‑commerce cart: use floats for percentage math, but store final amounts as integers (cents) to avoid rounding errors.
- Counting inventory items: integers guarantee exact counts; mixing floats in stock levels would cause fractional items.
- Scientific data analysis: floats handle large measurement ranges (e.g., temperature from -273.15 to 1e6 K) where exactness matters only within 15 decimal digits.
Key takeaways
- Integers are exact whole numbers; floats are approximate decimal numbers backed by binary hardware.
- In Python 3, the
/operator always returns a float; use//for integer (floor) division. - When mixing int and float in an operation, Python coerces the int to a float; the result is a float.
- Never compare floats with
==; use an epsilon tolerance likeabs(a - b) < 1e-10. - Use
int()to truncate toward zero, not to round;round()rounds to the nearest even integer. - Choose ints for exact counting and indexing; choose floats for continuous measurements and percentages.
Keep learning
Related tutorials, quizzes, and articles for this topic.
Discussion
Questions, corrections, and tips help everyone reading this page.
0 comments
Add a comment
No comments yet — start the thread.