A payment receipt generator is one of the best first Python projects for absolute beginners. It is small enough to finish in one sitting, practical enough to feel real, and it exercises variables, lists, loops, functions, and f-strings all at once.
Python is famous for letting you write useful programs with very little code. This tutorial builds that intuition by walking through a payment receipt generator from scratch. By the end you will have a working Python script that takes a list of purchased items, calculates a subtotal, applies a tax rate, and prints a clean formatted receipt to the terminal. Every line of code is explained before it is written.
What the Program Will Do
Before writing a single line of code it helps to picture the output. The finished program will print something like this to your terminal:
===========================
Corner Coffee Shop
===========================
Item Price
---------------------------
Coffee $3.50
Blueberry Muffin $2.75
Orange Juice $4.00
---------------------------
Subtotal $10.25
Tax (8%) $0.82
TOTAL $11.07
===========================
That output comes from four core ideas: a list holding the items, a loop that walks through the list, an f-string that formats each line, and a function that wraps it all together. Each of those ideas is introduced one at a time below.
Any Python 3 installation works. If you have Python 3.6 or later, all the code here will run without installing any third-party libraries. Open a terminal, type python --version, and confirm the output starts with 3.
Storing Items: Lists and Tuples
A receipt has a variable number of line items. The natural Python way to hold a collection of things is a list. Each element in this list will be a tuple — a pair of values grouped together: the item name and its price.
items = [
("Coffee", 3.50),
("Blueberry Muffin", 2.75),
("Orange Juice", 4.00),
]
The outer square brackets [ ] create a list. The inner parentheses ( ) create each tuple. A tuple with two values is sometimes called a pair. Here each pair holds a string (the item name) and a float (the price in dollars).
You can add as many tuples as you like. The for loop you will write later will handle any number of items automatically — you never have to count them yourself.
Tuples are a good choice for a name-price pair because the two values belong together and you do not need to change them after creation. Lists are used when you need a collection you might add to or remove from later.
Build a single tuple that stores the item name "Tea" and the price 2.50. Click each token in the correct order:
(), not square brackets. The correct form is ("Tea", 2.50) — the string name first, then a comma, then the float price, all wrapped in (). Using [ would create a list, not a tuple.
Printing with F-Strings
An f-string is a string that can embed variable values directly inside it. You write the letter f before the opening quote, and then put any variable name or expression inside curly braces { }. Python replaces those curly-brace expressions with their actual values when the string is printed.
name = "Coffee"
price = 3.50
print(f"{name:<20} ${price:.2f}")
The output of that single print line is:
Coffee $3.50
Two format specifiers appear inside the curly braces. The :<20 part tells Python to left-align the name inside a field 20 characters wide — this is what keeps all the prices lined up in a column. The :.2f part tells Python to display the float with exactly two decimal places, which is the standard format for currency.
"f-strings are faster and easier to read than older Python string formatting methods." — Python Software Foundation
- Syntax
f"Total: {total:.2f}"- When to use
- Your default choice in Python 3.6+. Clean, readable, and fast.
- Syntax
"Total: {:.2f}".format(total)- When to use
- Useful in Python 2 compatibility contexts or when building reusable template strings.
- Syntax
"Total: %.2f" % total- When to use
- Older style inherited from C. Still works but f-strings are preferred for new code.
The function below tries to print a formatted price line for a receipt item, but one line contains a bug. Click the line you think is wrong, then hit check.
f prefix. Without it, Python treats the curly braces as literal characters rather than embedding the variable values. The correct line is print(f"{name:<{width}} ${price:.2f}"). Note that width must also be inside its own curly braces inside the format spec to use the variable value.
The for Loop Over a List
A for loop runs a block of code once for each item in a sequence. When the sequence is a list of tuples, Python can unpack each tuple into separate variables in the same loop line. That is called tuple unpacking.
items = [
("Coffee", 3.50),
("Blueberry Muffin", 2.75),
("Orange Juice", 4.00),
]
subtotal = 0.0
for name, price in items:
print(f"{name:<20} ${price:.2f}")
subtotal += price
On each pass through the loop, name gets the first value of the tuple and price gets the second. The line subtotal += price is shorthand for subtotal = subtotal + price. After the loop finishes, subtotal holds the sum of all prices.
Initialise subtotal = 0.0 as a float, not 0 as an integer. When you add float prices to an integer zero Python will still produce a float, but starting with 0.0 makes your intent clear and avoids surprises with other formatting code.
How to Build a Payment Receipt Generator in Python
The steps below take everything from the sections above and assemble it into a single, complete script. Follow each step in order and you will have a working receipt generator by the end.
-
Define your items as a list of tuples
Create a variable called
itemsand assign it a list. Each element is a tuple containing a string (the item name) and a float (the price). This is the only data the rest of the program needs to operate. -
Write a function to print the receipt header
Define a function called
print_headerthat takes astore_nameparameter. Inside the function, print a separator line, the store name centered in a fixed-width field, another separator, and column labels. Use f-strings with the:^(center-align) format specifier for the store name. -
Loop over the items and accumulate the total
Initialise
subtotal = 0.0before the loop. Use afor name, price in items:loop to unpack each tuple. Inside the loop, print each line with the item name left-aligned in a 20-character field and the price right-aligned with two decimal places. Addpricetosubtotalon every iteration. -
Calculate tax and print the totals
After the loop, compute
tax = subtotal * TAX_RATEandtotal = subtotal + tax. Print a separator line followed by three footer lines showing the subtotal, tax amount (with the percentage label), and the grand total in uppercase. Keep all monetary values formatted with:.2f. -
Wrap everything in a generate_receipt function and call it
Place all the receipt logic inside a single function called
generate_receiptthat acceptsitems,store_name, andtax_rateas parameters. At the bottom of the file, call it with your data. Wrapping the logic in a function means you can generate receipts for different stores and item lists by calling the same function with different arguments.
The Complete Program
Here is the finished receipt generator with all five steps assembled into one script. Read through it top to bottom and notice how the pieces fit together before running it.
WIDTH = 27
TAX_RATE = 0.08
def generate_receipt(items, store_name, tax_rate=TAX_RATE):
"""Print a formatted payment receipt."""
sep = "=" * WIDTH
line = "-" * WIDTH
# Header
print(sep)
print(f"{store_name:^{WIDTH}}")
print(sep)
print(f"{'Item':<20} {'Price':>5}")
print(line)
# Line items
subtotal = 0.0
for name, price in items:
print(f"{name:<20} ${price:>4.2f}")
subtotal += price
# Totals
tax = subtotal * tax_rate
total = subtotal + tax
tax_label = f"Tax ({int(tax_rate * 100)}%)"
print(line)
print(f"{'Subtotal':<20} ${subtotal:>4.2f}")
print(f"{tax_label:<20} ${tax:>4.2f}")
print(f"{'TOTAL':<20} ${total:>4.2f}")
print(sep)
# --- Run the generator ---
purchases = [
("Coffee", 3.50),
("Blueberry Muffin", 2.75),
("Orange Juice", 4.00),
]
generate_receipt(purchases, "Corner Coffee Shop")
Save this to a file called receipt.py and run it with python receipt.py. The output should match the example at the top of this tutorial. Try changing the items list or adding new tuples — the totals and formatting will adjust automatically.
Add a second call to generate_receipt with a different list of items and a different store name. Because the logic lives inside a function, the same code produces a completely different receipt — no copying required.
Python Learning Summary Points
- A list of tuples is a clean way to store structured pairs of data such as item names and prices. The for loop can unpack each tuple in a single line using the
for name, price in items:pattern. - F-strings with format specifiers give you precise control over text alignment and decimal places. The
:<20spec left-aligns text in a 20-character field;:.2fformats a float to two decimal places — both essential for readable receipt output. - Wrapping receipt logic in a function with parameters like
items,store_name, andtax_ratemakes the program reusable. You can generate receipts for different stores and different item sets by calling the same function with different arguments.
This project covers the core building blocks that appear in virtually every Python program you will write going forward. Lists, loops, f-strings, and functions compose together in the same way here as they do in much larger applications — the scale changes but the patterns do not.
Frequently Asked Questions
You need variables, lists, for loops, functions, and f-strings. All of these are beginner-level concepts covered in this tutorial with working code examples.
An f-string lets you embed variable values directly inside a string by prefixing the string with f and placing variable names inside curly braces. For example, f'Total: {total}' inserts the value of total into the string at runtime.
You store multiple items in a list. A list is written with square brackets and items separated by commas, such as items = [("Coffee", 3.50), ("Sandwich", 7.25)]. Each item in this receipt example is a tuple containing a name and a price.
The for loop iterates over each item in the list, printing the name and price of each one and adding each price to a running total. It processes every item automatically without you having to write separate print statements for each one.
A function is a reusable block of code defined with the def keyword. In this project, the generate_receipt function wraps all the receipt logic so you can call it once with different data instead of repeating the same code.
Use an f-string with the :.2f format specifier, which tells Python to display a float with exactly two decimal places. For example, f'${price:.2f}' will output $3.50 for a price of 3.5.
Yes. This tutorial is written for absolute beginners. Every concept is introduced with an explanation before the code is shown, and the project is built one step at a time from variables up to a complete working receipt generator.
Multiply the subtotal by the tax rate expressed as a decimal. For example, tax = subtotal * 0.08 calculates 8% tax. Then add it to the subtotal to get the grand total: total = subtotal + tax.