int vs float — Know the Difference
The problem...
You've used numbers. You've done math.
But at some point, something unexpected happens.
You divide two numbers and get a decimal. You expect a whole number and get a float. Things don't behave the way you assumed.
Because int and float are not the same thing.
The idea!
Python has two distinct number types. They look similar. They behave differently.
Knowing the difference saves you from confusion later.
Making it real
a = 10 # int — whole number, no decimal point
b = 10.0 # float — has a decimal point
Same value. Different type.
print(type(a)) # <class 'int'>
print(type(b)) # <class 'float'>
In practice
x = 7
y = 2
print(x / y) # 3.5 — float, always
print(x // y) # 3 — int, floor division
print(x % y) # 1 — int, remainder
Division / always returns a float. Even when the result is whole:
print(10 / 2) # 5.0 — not 5
print(type(10 / 2)) # <class 'float'>
Converting between types
You can convert manually when you need to.
a = 3.9
print(int(a)) # 3 — truncates, does not round
b = 5
print(float(b)) # 5.0
int() does not round — it cuts off the decimal. Always.
Going further
When you mix int and float in an operation, Python returns a float.
print(5 + 2.0) # 7.0 — not 7
print(type(5 + 2.0)) # <class 'float'>
Python promotes to the more precise type automatically.
What's really happening
int and float are stored differently in memory. They behave differently in operations. And they produce different types of results.
Python handles most of this for you — but knowing what's happening underneath prevents surprises.
Heads up!
int(3.9)gives you3, not4— it truncates, never rounds- Division
/always returns float — use//if you need an int - Mixing int and float always produces a float
- Floats can have precision issues:
0.1 + 0.2is not exactly0.3in Python
The mindset shift
Stop thinking: "A number is a number."
Start thinking: "What type of number do I need — and what will Python give me?"
What you should understand now
- int and float are different types — even when the value looks the same
- Division always returns float
int()truncates, it does not round- Mixing int and float produces float