Beginner · First steps in Python · topic 4 of 50 · 20 min
Numbers and maths
Explanation
The basic operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
| + | add | 7 + 3 | 10 |
| - | subtract | 7 - 3 | 4 |
| * | multiply | 7 * 3 | 21 |
| / | divide (always gives a float) | 7 / 2 | 3.5 |
| // | floor division: divide and drop the decimal part | 7 // 2 | 3 |
| % | modulo: the remainder after division | 7 % 2 | 1 |
| ** | power | 2 ** 3 | 8 |
laddoos = 17
children = 5
print(laddoos // children) # each child gets
print(laddoos % children) # left overOrder of operations
Python follows the same order as school maths (BODMAS): brackets first, then powers, then multiply and divide, then add and subtract. Use brackets when you want to be sure.
print(2 + 3 * 4)
print((2 + 3) * 4)int and float
An int is a whole number like 25 or -3. A float is a number with a decimal point like 2.5. Dividing with / always gives a float, even when it divides evenly: 10 / 2 is 5.0.
print(0.1 + 0.2)
print(round(0.1 + 0.2, 2))Useful number functions
print(abs(-50)) # distance from zero: 50
print(round(3.14159, 2)) # 3.14
print(max(45, 78, 62)) # biggest: 78
print(min(45, 78, 62)) # smallest: 45
print(int("25") + 5) # turn text into a number: 30Short forms save typing. total += 50 means total = total + 50. The same works for -=, *= and /=.
wallet = 500
wallet -= 120 # bought a book
wallet += 200 # pocket money
print(wallet)Watch the lesson
Numbers and maths · 1/6
Python is a very good calculator. In this lesson you will learn its maths operators.
Prefer a video by a teacher? Find free videos on “python arithmetic operators floor division modulo” on YouTube ↗
In real life: Packing mangoes into boxes
A farmer in Ratnagiri has 1,250 mangoes. Each box holds 12. How many full boxes can he pack, and how many mangoes are left for his family? Floor division and modulo answer this in two lines.
mangoes = 1250
per_box = 12
print("Full boxes:", mangoes // per_box)
print("Left over:", mangoes % per_box)Practice (0/3 done)
Write a function boxes_needed(items, per_box) that returns how many FULL boxes you can pack. Example: boxes_needed(1250, 12) returns 104.
Write a function share(bill, people) that returns how much each person pays, rounded to 2 decimal places. Example: share(1000, 3) returns 333.33.
Write a function is_even(n) that returns True when n is even and False when it is odd.
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.