Python Numbers: int, float and Math Operators
Integers and Floats
Python has two main kinds of numbers. You met them in chapter 4; now let's see how they behave.
| Type | Meaning | Examples |
|---|---|---|
int | a whole number, no decimal point | 100, -5, 0 |
float | a number with a decimal point | 19.99, 2.5, 10.0 |
score = 100
price = 19.99
print(type(score))
print(type(price))<class 'int'> <class 'float'>
Think of an int as counting things you can't split, like people or goals, and a float as measuring things you can, like weight or money.
Mixing them
When you combine an int and a float, the answer is a float:
print(2 + 0.5)
print(3 * 1.0)2.5 3.0
3 * 1.0 is a whole amount, but because one side was a float, the result is 3.0.
Big numbers and underscores
For long numbers, you can use _ to make them easier to read. Python ignores it:
population = 1_400_000_000
print(population)1400000000
Floats are not always exact
Computers store floats in a way that can't hold every decimal exactly:
print(0.1 + 0.2)0.30000000000000004
This surprises everyone the first time! It's not a bug in Python; almost every programming language does it. You'll learn how to round the result in the last lesson of this topic.
Whole numbers are int, decimal numbers are float. Mix them, and you get a float.