Decimal Places
Division often gives a number with a lot of decimal places:
price = 10 / 3
print(price)This prints:
3.3333333333333335(The 5 at the end is a tiny inaccuracy: a computer stores most decimal numbers only approximately.)
That's no way to show a price. In an f-string, you can say how a number should look: after the value, write a colon and a format. The format .2f means two decimal places, and .1f one:
price = 10 / 3
print(f"Price: {price:.2f}")
print(f"{price:.1f}")
print(f"{2 / 3:.2f}")
print(f"{4.5:.2f}")
print(f"{5:.2f}")This prints:
Price: 3.33
3.3
0.67
4.50
5.00The f stands for a decimal number (in Python, a float), and the number after the dot says how many decimal places to show. The number is rounded: 2 / 3 is 0.666…, which shows as 0.67. When a number has fewer decimal places, zeros are added, so 4.5 shows as 4.50 and 5 as 5.00, the way prices are written.
The format changes only how the number is printed. The variable keeps its whole value, so you can go on calculating with it exactly:
average = 17 / 6
print(f"Average: {average:.1f}")
print(average)This prints:
Average: 2.8
2.8333333333333335A format with f works only for numbers. If the value is a text, for example a part you got from split(), the program ends with ValueError: Unknown format code 'f' for object of type 'str'. Turn the text into a number with float() first.
Instructions
- 1
Print each price in the list
priceswith two decimal places and a dollar sign right in front of it, each on its own line:$4.50,$12.25and$3.10. Keep the lines with the two lists: the exercise also tries other numbers in them. - 2
The list
ratingsholds the stars that customers gave the shop. Below, print their average with one decimal place:Rating: 4.2.