Rounding
The circumference of the sandpit came out as 12.566370614359172 meters, far more exact than anyone needs. Let's round it. For that, you don't need a module: round() is built into Python, like print() and len().
length = 12.566370614359172
print(round(length))
print(round(length, 1))
print(round(length, 2))13
12.6
12.57With one argument, round() rounds to a whole number and returns an int. The second argument says how many decimal places to keep, and then the result is a float.
Two results may surprise you:
print(round(2.5))
print(round(3.5))
print(round(2.675, 2))2
4
2.67When a number is exactly halfway between two whole numbers, round() goes to the even one, so 2.5 becomes 2, but 3.5 becomes 4. And 2.675 becomes 2.67, not 2.68, because the computer stores 2.675 a tiny bit lower. It's the same small inaccuracy that makes 0.1 + 0.2 come out as 0.30000000000000004.
round() isn't the same as :.2f from Working with Text, which only changes how a number is printed, always with two decimal places: f"{2.5:.2f}" is 2.50. round() gives you a new number to keep calculating with, and Python prints it without zeros at the end: round(2.5, 2) is 2.5. So print prices with :.2f, and use round() when you keep working with the value.
Sometimes the nearest whole number is the wrong answer. A school trip goes by buses with 20 seats each. For 52 students, 52 / 20 is 2.6, and rounding gives 3 buses, which is right. But for 45 students, 45 / 20 is 2.25, rounding gives 2 buses, and five students stay at home. Here you have to round up, whatever the decimals are. The module math has a function for each direction:
math.ceil()rounds up (ceil is short for ceiling, the top of a room).math.floor()rounds down (the floor is the bottom).
import math
print(math.ceil(45 / 20))
print(math.floor(45 / 20))
print(math.ceil(40 / 20))3
2
2A whole number stays as it is: 40 students fit exactly into 2 buses. Both functions return an int. For positive numbers, math.floor(a / b) gives the same as a // b from Python Basics. Rounding up has no operator, so math.ceil() is the one to remember.
Instructions
- 1
Every student needs a seat, and the last bus may leave with empty ones. Print how many buses the trip needs, with the label
Buses:. Calculate it fromstudentsandseats_per_buswithmath.ceil(): the exercise also tries other numbers of students. For 52 students, the program printsBuses: 3. - 2
Each bus costs
bus_price, and the students share the price of all the buses equally. Print what one student pays, rounded to two decimal places withround():Per student: 14.42.