Python Arena
Step 2 of 3

Decimals in f-strings

A division can give a number with many decimals, and printing it shows them all:

total = 10
people = 3
share = total / people
print(f"Each pays {share}")
Output
Each pays 3.3333333333333335

An f-string can say how a value should be shown. After the value inside the curly braces, write a colon and a format specifier. .2f means "as a decimal number with 2 decimals":

total = 10
people = 3
share = total / people
print(f"Each pays {share:.2f}")
print(f"Exactly: {share:.5f}")
print(f"Roughly: {share:.0f}")
Output
Each pays 3.33
Exactly: 3.33333
Roughly: 3

The number before the f is the number of decimals, and the last decimal is rounded: 2/3 with .2f is 0.67. The f stands for a float, a number with a decimal point. The value itself doesn't change: only the way it's shown.

The specifier adds decimals too, which is handy for prices. A whole number gets zeros after the point:

price = 4
discount = 0.5
print(f"{price:.2f} {discount:.2f} {price - discount:.2f}")
Output
4.00 0.50 3.50

The last value shows that a calculation can go inside the braces too, with the specifier after it.

An f-string is a string

An f-string doesn't have to go straight to print. It makes an ordinary string, which you can store in a variable, join with other strings or return from a function:

def receipt_line(item: str, price: float) -> str:
    return f"{item}: {price:.2f}"


line = receipt_line("Tea", 2.5)
print(line)
print(receipt_line("Cake", 3.75) + " (today's special)")
print(len(line))
Output
Tea: 2.50
Cake: 3.75 (today's special)
9

receipt_line returns the formatted text, and the code that calls it decides what to do with it. len(line) shows that line is an ordinary string of 9 characters.

Your task

Challenge 1 of 3

Fill in the blank with a format specifier, so the program prints the average with two decimals:

Average: 7.67

Challenge 2

Write a program that asks for the amount of a bill and the number of people sharing it, and prints how much each person pays, with two decimals:

Bill: 100
People: 3
Each pays 33.33

The bill may have decimals, so read it with float.

Challenge 3

Write the function price_tag(name: str, price: float) -> str, which returns a price tag with the price in two decimals. For example, price_tag("Coffee", 3.5) returns 'Coffee costs 3.50'.