Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 1.9 — Printing and f-strings
Python · Example 4 of 4

A receipt table with format specs

A for loop (Phase 2) repeats the indented lines once per item. Notice the widths, the commas, the percent, and how a spec can be nested with {width} and {precision}.

print shows values on the screen and can be tuned with sep and end. An f-string, written f"...{value}...", builds text by putting values into {} slots, and a format spec such as :.2f or :>8 controls how each value looks.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Set item = "Notebook", price = 45.5, qty = 3, and print Notebook: 3 x 45.50 = 136.50 with an f-string.

02

Print the number 1234567.891 with commas and one decimal place.

03

Print the three words red, green, blue on one line separated by | .

Explain it without notes

01

How do sep and end change what print does?

02

What is an f-string, and why is it better than joining strings with +?

03

Explain {value:>8}, {value:.2f} and {value:,}.

04

What is the difference between str(x) and repr(x)? When would you use repr?

A receipt table with format specs
Sign in to run this example in your browser.

Expected output

Item           Qty     Price      Total
---------------------------------------
Notebook         3     45.50     136.50
Pen             12      9.99     119.88
Geometry box     1    120.00     120.00
---------------------------------------
Grand total                      376.38
Share of box                      31.9%
[       3.142]
2.67 0 2 1_234_567.9 -5 0xff