Almost every program works with numbers. A shopping basket adds up prices, a game keeps score, a fitness app works out an average pace, and a budgeting script splits a bill between friends. Python is an excellent calculator: you can type sums straight into it and it gives the answer instantly.
Python has two main kinds of number. Integers (int) are whole numbers such as 7, 0 and -42. Floats (float) have a decimal point, such as 3.5 or 0.1. Python decides the type for you from the way you write the value, and converts between them when it needs to.
In this lesson you'll use all of Python's arithmetic operators, learn which ones are calculated first, round results neatly, meet a famous surprise with decimal numbers, and use the math and random modules for square roots, rounding up and random numbers.
Arithmetic operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Add | 7 + 2 | 9 |
- | Subtract | 7 - 2 | 5 |
* | Multiply | 7 * 2 | 14 |
/ | Divide | 7 / 2 | 3.5 |
// | Floor division (whole part) | 7 // 2 | 3 |
% | Remainder (modulo) | 7 % 2 | 1 |
** | Power | 7 ** 2 | 49 |
Normal division / always gives a float, even 8 / 2 is 4.0. Floor division // rounds down to a whole number, and % gives what's left over, which is perfect for questions like "is this number even?" (n % 2 == 0).
Mixing int and float, and negative division
When an expression mixes the two number types, Python converts the integer to a float so no precision is lost. 3 + 1.5 is 4.5, and even 2 * 1.0 is 2.0.
Floor division and remainder need extra care with negative numbers. // always rounds down, towards negative infinity, not towards zero:
| Expression | Result | Why |
|---|---|---|
7 // 2 | 3 | 3.5 rounded down |
-7 // 2 | -4 | -3.5 rounded down is -4, not -3 |
-7 % 2 | 1 | the remainder takes the sign of the divisor |
divmod(135, 60) | (2, 15) | quotient and remainder in one call |
divmod() is a tidy way to split a total into units, such as seconds into minutes and seconds. You can also write large numbers with underscores to make them readable: population = 8_100_000_000 is the same as 8100000000.
Order of operations and shorthand
Python follows the same rules as maths: brackets first, then powers, then multiplication and division, then addition and subtraction. So 2 + 3 * 4 is 14, while (2 + 3) * 4 is 20. When in doubt, add brackets: they make your intention obvious to anyone reading the code.
To change a variable based on its current value, use the shorthand operators:
score = 10
score += 5 # same as score = score + 5
score *= 2 # same as score = score * 2There are matching forms for every operator: -=, /=, //=, %= and **=.
Built-in number functions
round(x)rounds to the nearest whole number, andround(x, 2)to two decimal places.abs(x)gives the distance from zero, soabs(-8)is8.min()andmax()find the smallest and largest of several values.sum(list)adds up a list of numbers.int()andfloat()convert text or other numbers.int(3.9)cuts off the decimals and gives3.
Python integers can be as large as you like. 2 ** 100 works perfectly, with no overflow.
How round() handles .5
round() uses round half to even, sometimes called banker's rounding. When a number is exactly halfway between two whole numbers, Python picks the even one:
print(round(2.5)) # 2
print(round(3.5)) # 4
print(round(4.5)) # 4This avoids a slight upward bias when many halfway values are rounded, which matters in statistics and accounting. If you need "always round .5 up" behaviour, use the decimal module with ROUND_HALF_UP.
Because floats are stored in binary, a value that looks halfway may not be. round(2.675, 2) gives 2.67, because 2.675 is actually stored as 2.67499999... For display, an f-string such as f"{price:.2f}" is usually what you want.
Floating point surprises and the math module
Computers store floats in binary, so some decimals can't be stored exactly. That's why 0.1 + 0.2 prints 0.30000000000000004. It's not a Python bug: almost every language behaves this way. Round results before you show them, and compare floats with math.isclose() instead of ==.
The math module adds more tools:
import math
math.sqrt(16) # 4.0
math.ceil(4.2) # 5, round up
math.floor(4.8) # 4, round down
math.pi # 3.141592653589793For random numbers, import random gives you random.randint(1, 6) for a whole number between 1 and 6 inclusive, and random.choice(list) to pick an item.
Python Numbers Syntax
Number operations
a + b a - b a * b a / b
a // b a % b a ** b
x += 1
round(x, 2) abs(x) min(a, b) max(a, b)
import math
math.sqrt(x) math.ceil(x) math.floor(x)
import random
random.randint(1, 10)Python Numbers Summary
intis for whole numbers andfloatfor decimals;/always returns a float.//gives the whole part of a division and%the remainder.**raises to a power; brackets control the order of operations.+=,-=and friends update a variable using its current value.- Use
round()for display, and themathandrandommodules for more tools.
Python Numbers Examples
Each example shows the code, the output it produces and what each part does.
Splitting a restaurant bill
total = 87.60
people = 4
tip_percent = 10
tip = total * tip_percent / 100
each = (total + tip) / people
print("Tip:", round(tip, 2))
print("Each person pays:", round(each, 2))Tip: 8.76
Each person pays: 24.09Line-by-line explanation
- Line 5Multiplication and division happen left to right: 87.6 times 10, then divided by 100.
- Line 6Brackets make sure the tip is added before dividing.
- Lines 8 to 9round() keeps the output to two decimal places.
Minutes into hours, and even or odd
minutes = 135
hours = minutes // 60
left = minutes % 60
print(f"{minutes} minutes is {hours} h {left} min")
for n in [4, 7, 10]:
if n % 2 == 0:
print(n, "is even")
else:
print(n, "is odd")135 minutes is 2 h 15 min
4 is even
7 is odd
10 is evenLine-by-line explanation
- Line 2135 // 60 is 2, the number of whole hours.
- Line 3135 % 60 is 15, the minutes left over.
- Line 7A number is even when dividing by 2 leaves no remainder.
Using math and random
import math
import random
boxes = math.ceil(23 / 6)
print("Boxes needed for 23 eggs:", boxes)
print("Square root of 81:", math.sqrt(81))
roll = random.randint(1, 6)
print("You rolled a", roll)Boxes needed for 23 eggs: 4
Square root of 81: 9.0
You rolled a 5Line-by-line explanation
- Line 423 / 6 is about 3.83, and ceil rounds up, because 3 boxes wouldn't be enough.
- Line 6sqrt always returns a float.
- Line 8randint includes both ends. The roll is random, so your number may differ.
Common Python Numbers Mistakes
Expecting / to give a whole number
pages = 10 / 2
print(pages) # 5.0pages = 10 // 2
print(pages) # 5Comparing floats with ==
print(0.1 + 0.2 == 0.3) # Falseimport math
print(math.isclose(0.1 + 0.2, 0.3)) # TrueDoing maths with text from input()
age = input("Age: ")
print(age + 1) # TypeErrorage = int(input("Age: "))
print(age + 1)input() always returns a string, so convert it before calculating.
Python Numbers in Real Projects
Numbers in real programs
Shops calculate totals, tax and discounts; fitness apps convert seconds into minutes and kilometres into miles; games use random numbers for dice and enemy movement; and data analysts calculate averages and percentages across millions of rows. Python's simple number syntax is a big reason it's popular in finance, science and data work.
Python Numbers FAQ
Why does round(2.5) return 2 in Python?
Python 3 rounds exact halves to the nearest even number, so round(2.5) is 2 and round(3.5) is 4. This is a deliberate choice that reduces bias when rounding many values. Use the decimal module with ROUND_HALF_UP if your task needs traditional rounding.
What is the difference between / and // in Python?
/ is true division and always returns a float: 9 / 2 is 4.5. // is floor division: it divides and rounds down to a whole number, so 9 // 2 is 4. If either operand is a float, // returns a float such as 4.0.
How do I format a number with commas or a fixed number of decimals?
Use a format specification inside an f-string. f"{1234567:,}" gives 1,234,567, f"{3.14159:.2f}" gives 3.14, and f"{0.256:.1%}" gives 25.6%. Formatting changes only the text you display, not the stored value.
Is there a maximum integer size in Python?
No fixed one. Python integers grow as large as your computer's memory allows, so 2 ** 1000 works without overflow. Floats are different: they are 64-bit values with about 15 to 17 significant digits, and very large results become inf.
How do I get a random decimal number instead of a whole number?
random.random() returns a float from 0.0 up to, but not including, 1.0. random.uniform(1.5, 4.5) returns a float between the two values you give it. Use random.randint() only when you want whole numbers.
Python Numbers Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Complete the code so it prints the remainder when 17 is divided by 5.
print(17 5)
What does this print?
print(9 / 3, 9 // 2)
What does this print?
x = 4
x += 2
x *= 3
print(x)
Which expression equals 20?
You need enough buses for 130 people, 50 per bus. Which gives the right answer?
Python Numbers Quiz
5 questions to check what you learned.
What does
2 ** 3equal?- 8
- 6
- 5
- 9
What type is the result of
10 / 5?- int
- str
- bool
- float
What does
round(3.14159, 2)return?- 3.14
- 3.1
- 3.142
- 3
Why does
0.1 + 0.2print0.30000000000000004?- Python has a bug
- The numbers are strings
- Some decimals can't be stored exactly in binary
- round() was missing
What does
-7 // 2give?- -3
- -3.5
- 3
- -4