python · level 2 · unit 3 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A tells an f-string how to show a number.
Inside an f-string's curly brackets, add a colon after the value, then a format spec. {price:.2f} shows price with exactly two , so 4.5 becomes 4.50. Money looks right at last.
This is for display only: 2.678 shows as 2.68, but the value in the box does not change.
{crowd:,} puts commas between the thousands, and {share:.0%} turns 0.25 into 25%. You can mix them: {total:,.2f} gives 1,234.50.
price = 4.5
print(f"£{price:.2f}")
print(f"{2.678:.2f}")
crowd = 52341
print(f"{crowd:,} fans")
share = 0.25
print(f"{share:.0%} of the pizza")
print(f"£{1234.5:,.2f}") The f in .2f stands for fixed: a fixed number of decimal places.
guess first
Splitting the bill three ways. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
bill = 50
each = bill / 3
print(each)
print(f"£{each:.2f} each")
your turn
Your turn. Print a price tag.
Type a price and a quantity. Then fill in the format spec so the total shows as money, with two decimal places.
fix it
The sale sign has too many digits. Can you fix it?
- The price shows six decimal places. Look closely at the format spec inside the curly brackets.
- Without a dot, the 2 means something else. A dot before the 2 is what sets the decimal places.
- Change :2f to :.2f on line 3, then run.
nailed it
your numbers look professional now. :D
{value:.2f}shows exactly two decimal places.{value:,}adds commas, and{value:.0%}shows a percentage.- Formatting changes how a number looks, never its value.
new words in your collection
- format spec
- decimal places
- rounding
This lesson isn’t saved. A free account remembers every lesson you finish.