The math toolbox
Built-in tools need no import: round(x, 2) rounds x to 2 decimal places (an exact half goes to the even neighbour, so round(2.5) is 2 and round(3.5) is 4), abs(-4) gives the distance from zero (4), max(3, 9) gives the largest value (9), and min(3, 9) gives the smallest (3).
More tools live in the math module. Import it once at the top:
import math math.pi # 3.14159... math.sqrt(16) # 4.0 math.ceil(4.1) # 5 (round up) math.floor(4.9) # 4 (round down)
See it run
import math x = 7.6 print(round(x), math.floor(x), math.ceil(x)) print(math.sqrt(49))
import math unlocks extra tools. Watch how three ways of rounding treat the same number.
Practice the math toolbox
Exercise 1
area: the area of a circle withradius = 3(π × r²), rounded to 2 decimals (28.27).boxes: you need to ship 23 cups, 5 per box. How many boxes? Usemath.ceil(5).
Exercise 2
TV sizes are measured corner to corner. A screen is width = 16 and height = 9 (inches).
Make diagonal = √(width² + height²) using math.sqrt, rounded to 1 decimal (18.4).
Exercise 3
You are painting a wall 4.2 m wide and 2.6 m tall with 2 coats. One tin covers 10 m².
area_needed= width × height × coats, rounded to 2 decimals (21.84)tins= how many tins to buy (you can't buy part of a tin): 3leftover= m² of paint left over, rounded to 2 decimals (8.16)
Free lesson: use the editor to practice it.
Practice
Loading Python…Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.