blog / guides

python print() examples you can try yourself

by Luke published 8 min read

the short answer

print() can do much more than show one line of text. Format codes inside f-strings line up columns, add commas to big numbers and pad times with zeros. The star unpacks a list into separate values. end keeps several prints on one line, and a loop turns print into a pattern maker. The ten examples here show each trick with code you can run and its output.

print() can do far more than show one line of text. With a few format codes and two keyword arguments, it can lay out receipts, draw patterns, count down and tidy up numbers. This page is a set of ten small examples to run, read and borrow.

If you are new to print(), start with our guide to Python’s print() function, which covers quotes, commas, sep, end and the basics of f-strings. Everything here builds on that.

1. A receipt with lined-up prices

try it · python
items = [("Tea", 2.5), ("Toastie", 5.25), ("Flapjack", 2.75)]
for name, price in items:
    print(f"{name:<10}£{price:>6.2f}")
print("-" * 17)
print(f"{'Total':<10}£{sum(p for n, p in items):>6.2f}")
Tea       £  2.50
Toastie   £  5.25
Flapjack  £  2.75
-----------------
Total     £ 10.50

Inside the curly brackets, after a colon, you can say how wide each value should be:

  • <10 pads to 10 characters with the text on the left.
  • >6.2f gives a 6-character space with the number on the right and two decimal places.
  • ^, not used here, centres the value.

"-" * 17 repeats a dash 17 times, which makes a quick divider line.

2. Big numbers and percentages

try it · python
visitors = 1234567
share = 0.256
print(f"{visitors:,} visitors")
print(f"{share:.1%} came from search")
print(f"£{9876543.21:,.2f} raised")
1,234,567 visitors
25.6% came from search
£9,876,543.21 raised

A comma adds thousands separators. % multiplies by 100 and adds the percent sign, so you never have to do it by hand.

3. A list without the brackets

try it · python
names = ["Ava", "Ben", "Cal"]
print(names)
print(*names)
print(*names, sep=", ")
print(*names, sep="\n")
['Ava', 'Ben', 'Cal']
Ava Ben Cal
Ava, Ben, Cal
Ava
Ben
Cal

The star unpacks the list, so print(*names) is the same as print("Ava", "Ben", "Cal"). That is why sep works on it.

4. A progress bar

try it · python
for done in [2, 5, 10]:
    bar = "#" * done + "." * (10 - done)
    print(f"[{bar}] {done * 10}%")
[##........] 20%
[#####.....] 50%
[##########] 100%

Multiplying text repeats it, so the bar is always ten characters wide: some hashes for the part done, and dots for the rest. Change the 10 to 20 in both places for a finer bar, and multiply done by 5 instead of 10 to keep the percentages right.

5. A countdown on one line

try it · python
for n in range(5, 0, -1):
    print(n, end=" ")
print("Lift off!")
5 4 3 2 1 Lift off!

range(5, 0, -1) counts down from 5, stopping before 0. end=" " swaps the usual new line for a space, so the numbers stay on one line until the last print.

6. A clock with leading zeros

try it · python
for hour, minute in [(7, 5), (12, 30), (21, 0)]:
    print(f"{hour:02d}:{minute:02d}")
07:05
12:30
21:00

02d means a whole number at least two digits wide, padded with zeros. Without it, the first time would show as 7:5, which nobody would read as five past seven.

7. A triangle pattern

try it · python
for row in range(1, 5):
    print("*" * row)
print()
for row in range(1, 5):
    print(f"{'*' * (row * 2 - 1):^7}")
*
**
***
****

   *
  ***
 *****
*******

The first triangle prints one more star on each row. The second makes an odd number of stars and centres each row in seven characters with ^7. Patterns like these are a classic way to practise loops.

8. Checking values while you debug

try it · python
price = 4.5
quantity = 3
total = price * quantity
print(f"{price=}, {quantity=}, {total=}")
price=4.5, quantity=3, total=13.5

An equals sign after the name prints both the name and its value. When a program gives a strange answer, one line like this shows you what every variable really holds.

9. A table with a header

try it · python
scores = [("Ava", 42), ("Ben", 7), ("Cal", 128)]
print(f"{'Name':<6}{'Score':>6}")
print("=" * 12)
for name, score in scores:
    print(f"{name:<6}{score:>6}")
Name   Score
============
Ava       42
Ben        7
Cal      128

Numbers line up best on the right, so the units, tens and hundreds sit in the same columns.

10. Several lines at once

try it · python
menu = """Today's menu
------------
Soup     £4
Pie      £7
Crumble  £3"""
print(menu)
Today's menu
------------
Soup     £4
Pie      £7
Crumble  £3

Three quote marks make text that can run over several lines, kept exactly as you typed it. It is the easiest way to print a block like a menu, some instructions or a title screen.

The format codes in one place

Every trick above that lines things up or tidies a number uses the same layout inside the curly brackets: the value, a colon, then the format code. Here are the ones from this page, ready to borrow:

  • {x:<10} left-aligns in 10 characters. Text does this by default.
  • {x:>10} right-aligns in 10 characters. Numbers do this by default.
  • {x:^10} centres in 10 characters.
  • {x:.2f} shows two decimal places.
  • {x:,} adds thousands separators.
  • {x:.1%} shows a fraction as a percentage with one decimal place.
  • {x:02d} pads a whole number to two digits with zeros.
  • {x=} shows the name, an equals sign and the value.

Codes combine in a fixed order: alignment, then width, then the comma, then the decimals. So {x:>12,.2f} means right-aligned in 12 characters, with separators and two decimal places.

Putting it together: a payslip

This last example uses several codes at once to print a payslip that would not look out of place on paper:

try it · python
name = "Jo Brown"
hours = 37.5
rate = 12.60
gross = hours * rate
print(f"{'PAYSLIP':^24}")
print("=" * 24)
print(f"{'Name':<12}{name:>12}")
print(f"{'Hours':<12}{hours:>12.1f}")
print(f"{'Rate (£)':<12}{rate:>12.2f}")
print("-" * 24)
print(f"{'Gross (£)':<12}{gross:>12,.2f}")
        PAYSLIP
========================
Name            Jo Brown
Hours               37.5
Rate (£)           12.60
------------------------
Gross (£)         472.50

Every line is 24 characters wide: a 12-character label on the left and a 12-character value on the right. Keeping the widths the same on every line is what makes the columns sit neatly under each other. The pound sign sits in the labels so the numbers stay plain numbers and line up by their decimal points.

Common mistakes

A number format on text

try it · python
price = "4.50"
print(f"£{price:.2f}")
  File "<exec>", line 2, in <module>
ValueError: Unknown format code 'f' for object of type 'str'

.2f only works on numbers. Here price is text, because of the quotes. Convert it first with float(price), or store it as a number in the first place.

Forgetting the f

try it · python
total = 13.5
print("Total: {total}")
Total: {total}

Without the f in front of the quote, the curly brackets are just characters. Python shows them as they are.

A width that is too small

try it · python
for name in ["Ann", "Bartholomew"]:
    print(f"{name:<6}|")
Ann   |
Bartholomew|

A width is a minimum, not a limit. Python never cuts a value short to fit, so one long name pushes its whole row out of line. Make the width at least as big as your longest value, or work it out from the data with max(len(n) for n in names).

Leaving end on

After print("Loading", end=""), the next print carries on from the same line. If your output looks squashed together, check for an end left over from earlier, and add an empty print() to finish the line.

A star on text

print(*"abc") prints a b c, because the star unpacks text into its letters. Use it on lists, not on strings, unless that is what you want.

A short exercise

Print a league table from this list, with names on the left in 8 characters and points on the right in 4, under a header and a line of dashes:

teams = [("Lions", 21), ("Tigers", 9), ("Bears", 15)]

Try it in the playground from the button at the bottom of the page, choosing Python.

One possible answer

try it · python
teams = [("Lions", 21), ("Tigers", 9), ("Bears", 15)]
print(f"{'Team':<8}{'Pts':>4}")
print("-" * 12)
for team, points in teams:
    print(f"{team:<8}{points:>4}")
Team     Pts
------------
Lions     21
Tigers     9
Bears     15

For an extra challenge, sort the teams by points first. sorted(teams, key=lambda t: t[1], reverse=True) gives the list from most points to fewest.

Your next step

Clear output makes every program nicer to use, and these tricks come up again and again. Gwecode’s Python Level 1 covers printing in its first lessons, then has a lesson on putting values inside text, before moving on to decisions, loops and functions. Its level check is a tiny quiz game you build yourself. Every lesson is free and runs in your browser. Create a free account to keep your progress, and try the lesson below.

practise this · python · lessonPutting values inside textstart the lesson

questions

How do I line up columns with print?

Use an f-string with a width: {name:<10} pads text to 10 characters on the left, and {price:>7.2f} puts a number on the right of a 7-character space with two decimal places.

How do I print a number with commas?

Add a comma format code: f"{1234567:,}" shows 1,234,567. Combine it with decimals as {amount:,.2f}.

How do I print a list without brackets?

Put a star before it: print(*names). Each item becomes a separate value, so sep controls what goes between them, as in print(*names, sep=", ").

How do I print a variable’s name and value together?

Add an equals sign inside an f-string: print(f"{total=}") shows total=30. It is a quick way to check values while debugging.

How do I print a number with a leading zero?

Use the format code 02d, as in f"{7:02d}", which shows 07. It is handy for times and dates.

keep going.