Print Function
The round function returns a number rounded to a stated number of decimal places. You give the value first, then the number of decimal places: round(8.6742, 2) gives 8.67. The result is a real number, so you can print it, store it in a variable or use it in a later calculation. Rounding does not pad a number with zeros, so 6.5 rounded to two decimal places is still 6.5 and prints as 6.5 rather than 6.50: the trailing zero is not part of the number.
Because round hands back a number rather than text, it suits a plain print where no layout is needed, and arithmetic that carries on afterwards. This program finds an average lap time in a kart race and shows both the tidy version and the precise one.
total_time = 47.368 # seconds for three laps
laps = 3
average_lap = total_time / laps
print('Average lap to one decimal place: ' + str(round(average_lap, 1)))
print('Average lap kept in full: ' + str(average_lap))Output:
Average lap to one decimal place: 15.8
Average lap kept in full: 15.789333333333333The variable still holds the full result, so the second print can show it exactly, and adding to, multiplying or comparing the rounded value works normally.
A format specification does a similar job for display: placed inside a placeholder of a template string, it shows a value to a stated number of decimal places and keeps trailing zeros, so 6.5 appears as 6.50. It produces text for the screen only, so it cannot be used in a calculation, and the variable itself is untouched.
Formatting only changes the text that is displayed, and round only returns a new number; neither alters the value already stored in a variable. Storing a rounded or formatted result back into the variable does change it, and that loses precision, making later output inaccurate.
mass = 7.4562 # kilograms
mass = round(mass, 1)
print('Stored mass: ' + str(mass))
print('Twice the stored mass: ' + str(mass * 2))Output:
Stored mass: 7.5
Twice the stored mass: 15.0Doubling the exact mass would give 14.9124, but the rounded figure was stored back into the variable, so the last print works from a value that is already too rough.
Edexcel GCSE Computer Science · Print Function