# PYTHON # CODING đŸ‘ī¸ 11 views âąī¸ 14 min read

Python Tutorial for Beginners: Build a Simple Cashier Application in 30 Minutes

Want to learn Python with a real-world project? Follow this tutorial to build a functional simple cashier application, perfect for beginners looking for quick results.

aplikasi kasih python
aplikasi kasih python

Ever wondered how cashier applications in small shops or convenience stores work? Or do you want a simple tool to record your online sales transactions? You've come to the right place!

In this Python tutorial for beginners, we'll dive straight into building a simple cashier application. We won't dwell on theory; instead, we'll focus on code that you can follow step-by-step. The goal is clear: after 30 minutes, you'll have a functional cashier program running on your computer, ready for practice or even to assist your business!

Prepare your code editor and your enthusiasm, because we're about to embark on an exciting coding adventure. You'll learn many fundamental concepts that are incredibly useful in the world of software development.

  • Creating a list of products and their prices.
  • Receiving user input (selecting products and quantities).
  • Calculating the total bill.
  • Processing payments and calculating change.
  • Using basic Python control structures (loops and conditionals).
  • Building a text-based interactive application.

What is a Simple Cashier Application?

Simply put, a cashier application is a program that helps us record sales, calculate the total price of items purchased by customers, and process payments. It's the operational backbone of many retail businesses, from small coffee shops to large supermarkets.

In the context of the simple cashier application we're building, this program will interact with the user via text (terminal). You'll be able to select items from a menu list, enter quantities, view the total bill, and then input the amount paid by the customer to calculate change. Think of it as a smart calculator that can remember a list of items and their prices, then automatically calculate everything needed for a sales transaction.

â„šī¸ Info: More complex cashier applications typically integrate with a database to store product data, inventory, transaction history, and even connect to receipt printers. But for beginners, we'll focus on the core transaction logic first!

Preparation

Before we start coding, there are a few things you need to prepare:

  • Python 3.8 or newer: Make sure you have Python installed on your computer. Version 3.8 and above is a good standard in 2026.
  • Text Editor: Visual Studio Code, Sublime Text, Atom, or even Notepad++ will suffice. VS Code is highly recommended due to its comprehensive features for developers.
  • Basic Python Knowledge: You should at least be familiar with concepts like variables, data types (string, integer, float), basic operators, and control structures such as if/else and for/while loops.

Let's check if Python is installed correctly. Open your terminal or Command Prompt and run the following command:

python3 --version
# or if python3 is not found, try:
python --version

You should see output indicating the installed Python version, for example:

Python 3.10.6

If you see an error message or the command is not found, please install Python first from the official Python website.

Step 1: Creating the Project Structure and Product List

In this first step, we'll create the main Python file and define the list of products to be sold in our cashier application.

Create a new folder on your computer (e.g., cashier_app), then inside it, create a file named kasir.py:

# kasir.py

# List of available products in the store
# Using a dictionary to store product names and their prices
# Key is the product name, Value is the price
daftar_produk = {
    "kopi": 15000,
    "teh": 10000,
    "roti": 12000,
    "mie instan": 5000,
    "air mineral": 3000
}

print("Welcome to Simple Cashier!")
print("Product List:")
for produk, harga in daftar_produk.items():
    print(f"- {produk.capitalize()}: Rp{harga:,}")

# We will add the cashier logic in the next step

Code explanation:

  • daftar_produk: This is a Python dictionary. We use it to store product data. Each product has a name (string, as a key) and a price (integer, as a value).
  • for produk, harga in daftar_produk.items():: We use a for loop to iterate over each key-value pair (product and price) in the daftar_produk dictionary.
  • print(f"- {produk.capitalize()}: Rp{harga:,}"): This is an f-string, a modern way in Python to format strings.
    • produk.capitalize(): Capitalizes the first letter of the product name for a neater appearance.
    • harga:,: This is a format specifier in f-strings that will add a comma as a thousands separator (e.g., 15000 becomes 15,000).

Run this file from your terminal:

python3 kasir.py
# or
python kasir.py

Expected output:

Welcome to Simple Cashier!
Product List:
- Kopi: Rp15,000
- Teh: Rp10,000
- Roti: Rp12,000
- Mie instan: Rp5,000
- Air mineral: Rp3,000

Step 2: Receiving Customer Orders

Now, let's add logic to allow customers to select products and their desired quantities. We'll store their orders in a shopping cart.

Edit your kasir.py file:

# kasir.py

daftar_produk = {
    "kopi": 15000,
    "teh": 10000,
    "roti": 12000,
    "mie instan": 5000,
    "air mineral": 3000
}

keranjang_belanja = [] # List to store purchased items

print("Welcome to Simple Cashier!")
print("Product List:")
for produk, harga in daftar_produk.items():
    print(f"- {produk.capitalize()}: Rp{harga:,}")

# Main loop to receive orders
while True:
    print("\n--- Enter Order ---")
    nama_produk = input("Product name (type 'done' to checkout): ").lower()

    if nama_produk == 'done':
        break # Exit loop if user types 'done'

    if nama_produk in daftar_produk:
        while True:
            try:
                jumlah = int(input(f"Quantity of {nama_produk.capitalize()}: "))
                if jumlah > 0:
                    keranjang_belanja.append({"produk": nama_produk, "jumlah": jumlah, "harga": daftar_produk[nama_produk]})
                    print(f"{jumlah} {nama_produk.capitalize()} added to cart.")
                    break # Exit quantity input loop if valid
                else:
                    print("Quantity must be greater than 0.")
            except ValueError:
                print("Invalid quantity input. Please enter a number.")
    else:
        print("Product not found. Please check the product list again.")

# We will add total calculation and payment in the next step

Code explanation:

  • keranjang_belanja = []: This is an empty list that we'll use to store each item selected by the customer. Each item will be a dictionary containing produk, jumlah, and harga per unit.
  • while True:: This is an infinite loop that will continue to run until we explicitly stop it with break. This allows customers to keep adding items to the cart.
  • input("Product name..."): The input() function is used to receive input from the user. .lower() converts the input to lowercase to match the keys in daftar_produk.
  • if nama_produk == 'done': break: If the user types "done", the loop will stop, and we'll proceed to the checkout process.
  • if nama_produk in daftar_produk:: Checks if the product entered by the user exists in our product list.
  • try-except ValueError: This is an error handling block. If the user enters text (not a number) when prompted for quantity, int() will fail and trigger a ValueError. The except block will catch this error and display a more user-friendly message.
  • keranjang_belanja.append(...): Appends a new dictionary representing the ordered item to keranjang_belanja.

Try running kasir.py again and enter some orders:

python3 kasir.py

Example interaction:

Welcome to Simple Cashier!
Product List:
- Kopi: Rp15,000
- Teh: Rp10,000
- Roti: Rp12,000
- Mie Instan: Rp5,000
- Air Mineral: Rp3,000

--- Enter Order ---
Product name (type 'done' to checkout): kopi
Quantity of Kopi: 2
2 Kopi added to cart.

--- Enter Order ---
Product name (type 'done' to checkout): roti
Quantity of Roti: 1
1 Roti added to cart.

--- Enter Order ---
Product name (type 'done' to checkout): jus
Product not found. Please check the product list again.

--- Enter Order ---
Product name (type 'done' to checkout): teh
Quantity of Teh: tiga
Invalid quantity input. Please enter a number.
Quantity of Teh: 3
3 Teh added to cart.

--- Enter Order ---
Product name (type 'done' to checkout): done

Step 3: Calculating the Total Bill

Once all orders are collected, it's time to calculate the total amount the customer needs to pay. We'll iterate through the shopping cart and sum up all subtotals.

Add the following code to the bottom of your kasir.py file, after the while True loop:

# kasir.py

# ... (previous code) ...

# This section is added after the order loop finishes
total_belanja = 0
if not keranjang_belanja: # Check if cart is empty
    print("\nShopping cart is empty. No transaction.")
else:
    print("\n--- Bill Details ---")
    print("-" * 30) # Separator line
    for item in keranjang_belanja:
        subtotal = item["jumlah"] * item["harga"]
        print(f"{item['produk'].capitalize()} ({item['jumlah']}x) @ Rp{item['harga']:,} = Rp{subtotal:,}")
        total_belanja += subtotal
    print("-" * 30)
    print(f"Total Bill: Rp{total_belanja:,}")

# We will add the payment process in the next step

Code explanation:

  • total_belanja = 0: A variable to store the accumulated total price.
  • if not keranjang_belanja:: Checks if the keranjang_belanja list is empty. If so, it means no items were ordered.
  • for item in keranjang_belanja:: A loop for each item in the cart.
  • subtotal = item["jumlah"] * item["harga"]: Calculates the subtotal for each type of item.
  • total_belanja += subtotal: Adds the subtotal to total_belanja.

Run it again and try to checkout:

python3 kasir.py

Example output (after entering orders and typing 'done'):

... (order interaction) ...
Product name (type 'done' to checkout): done

--- Bill Details ---
------------------------------
Kopi (2x) @ Rp15,000 = Rp30,000
Roti (1x) @ Rp12,000 = Rp12,000
Teh (3x) @ Rp10,000 = Rp30,000
------------------------------
Total Bill: Rp72,000

Step 4: Payment Processing and Change Calculation

The final step in the transaction cycle is to receive payment from the customer and calculate their change. We also need to handle cases where the amount paid is insufficient.

Add the following code to the bottom of your kasir.py file, after displaying the total bill:

# kasir.py

# ... (previous code) ...

# This section is added after the total bill calculation
if total_belanja > 0: # Only process payment if there's a total bill
    print("\n--- Payment Process ---")
    while True:
        try:
            uang_dibayar = int(input(f"Total due: Rp{total_belanja:,}\nAmount paid: Rp"))
            if uang_dibayar < total_belanja:
                print(f"Insufficient amount: Rp{(total_belanja - uang_dibayar):,}. Please add more.")
            else:
                kembalian = uang_dibayar - total_belanja
                print(f"Change: Rp{kembalian:,}")
                print("\nThank you for shopping!")
                break # Exit payment loop if payment is sufficient
        except ValueError:
            print("Invalid amount paid input. Please enter a number.")

Code explanation:

  • if total_belanja > 0:: Ensures the payment process only runs if there's a total bill to be paid.
  • while True:: A loop to ensure the received payment is sufficient.
  • try-except ValueError: Again, error handling for the amount paid input.
  • if uang_dibayar < total_belanja:: A condition to check if the amount paid is less than the total bill.
  • kembalian = uang_dibayar - total_belanja: Calculates the change.

Run kasir.py again and complete the entire transaction process:

python3 kasir.py

Full example output:

Welcome to Simple Cashier!
Product List:
- Kopi: Rp15,000
- Teh: Rp10,000
- Roti: Rp12,000
- Mie Instan: Rp5,000
- Air Mineral: Rp3,000

--- Enter Order ---
Product name (type 'done' to checkout): kopi
Quantity of Kopi: 1
1 Kopi added to cart.

--- Enter Order ---
Product name (type 'done' to checkout): mie instan
Quantity of Mie Instan: 2
2 Mie Instan added to cart.

--- Enter Order ---
Product name (type 'done' to checkout): done

--- Bill Details ---
------------------------------
Kopi (1x) @ Rp15,000 = Rp15,000
Mie Instan (2x) @ Rp5,000 = Rp10,000
------------------------------
Total Bill: Rp25,000

--- Payment Process ---
Total due: Rp25,000
Amount paid: Rp20000
Insufficient amount: Rp5,000. Please add more.
Total due: Rp25,000
Amount paid: Rp30000
Change: Rp5,000

Thank you for shopping!
💡 Tips: You can make this entire process run continuously to serve multiple transactions by wrapping all the logic from "welcome" to "thank you" in another while True loop, then adding options to start a new transaction or exit. However, to keep this tutorial concise and focused, we'll conclude it here.

Common Errors and How to Resolve Them

As a beginner, you might encounter some common errors. Don't worry, it's part of the learning process! Here are some frequent ones:

ValueError: invalid literal for int() with base 10: '...'

Cause: This error occurs when you try to convert a non-numeric string (e.g., "two" or "abc") into an integer using the int() function. This often happens when receiving user input.

Solution: Use a try-except ValueError block, as we've implemented in steps 2 and 4. This will gracefully handle invalid input without crashing the program.

try:
    jumlah = int(input("Enter a number: "))
except ValueError:
    print("Invalid input. Please enter a number.")

KeyError: 'nama_produk_tidak_ada'

Cause: This error occurs when you try to access a key in a dictionary that does not exist. For example, you might look for daftar_produk["juice"] when "juice" is not in daftar_produk.

Solution: Always check for the existence of a key before attempting to access it. We've already done this with if nama_produk in daftar_produk:. Another alternative is to use the .get() method, which will return None (or a default value you specify) if the key is not found, instead of raising an error.

# Solution already used:
if nama_produk in daftar_produk:
    # Continue process
else:
    print("Product not found.")

# Alternative with .get():
harga = daftar_produk.get(nama_produk)
if harga is not None:
    # Product found
else:
    print("Product not found.")

IndentationError: expected an indented block

Cause: Python is very strict about indentation (spaces or tabs at the beginning of a line). This error occurs if you have a code block (e.g., after if, for, while, or function definitions) but don't indent it correctly, or if there's an indentation mismatch (e.g., a mix of spaces and tabs).

Solution: Double-check your indentation. Ensure all lines within a block have a consistent number of spaces (usually 4 spaces) or tabs. Most modern code editors will automatically assist with indentation.

Tips and Best Practices

Here are some tips for further developing this cashier application and best practices in coding:

  • Modularize Code with Functions: For larger applications, separate the logic into several functions (e.g., display_menu(), take_order(), calculate_total(), process_payment()). This makes the code easier to read, test, and maintain.
  • Further Input Validation: Besides checking data types, you can add other validations. For example, ensuring the quantity entered is not negative or zero (which we've already done), or ensuring the product name is not empty.
  • Using Constants: For values that don't change (like the product list), consider storing them in variables with uppercase names (e.g., PRODUCT_LIST) to indicate they are constants.
  • Add Clear Comments: Although the code we've written is quite simple, always make it a habit to add comments (starting with #) to explain complex or less obvious parts of the code. This is very helpful when you or others reread your code later.
  • Automatic Cart Clearing: If you want this application to handle continuous transactions, make sure to clear keranjang_belanja and reset total_belanja after each transaction is complete, before starting a new one.
💡 Tips: To keep the code clean, avoid "magic numbers" (numbers that appear out of nowhere). If there's a 10% tax, define it as SALES_TAX_RATE = 0.10. This makes the code easier to understand and modify.

FAQ

How can I add discounts to this cashier application?

To add discounts, you can create a new function that takes the total bill and a discount percentage. This function would calculate the discount amount and subtract it from the total bill. You could add an option to apply the discount before the payment process.

Can product data be stored permanently so it's not lost when the program closes?

Absolutely! There are several ways. For simple projects, you can store the product list in plain text files, CSV (Comma Separated Values), or JSON. For more serious applications, you would use a database like SQLite (which is included with Python), PostgreSQL, or MySQL.

Is it possible to create this cashier application with a graphical interface (GUI)?

Absolutely! Python has several popular GUI libraries, such as Tkinter (which comes pre-installed with Python), PyQt, or Kivy. With these libraries, you can create windows, buttons, input boxes, and other visual elements to build a more interactive and visually appealing application.

Conclusion

Congratulations! You have successfully completed this Python tutorial for beginners and built a fully functional simple cashier application. You've learned how to manage product data, receive user input, perform calculations, and handle basic transaction flow.

This is an excellent foundation for your future Python projects. From here, you can further develop this cashier application. Here are some ideas for your next steps:

  • Add Discount or Tax Features: Try implementing logic to apply discounts to the total bill or add taxes.
  • Save Transaction History: Use plain text files or the json module to save each completed transaction to a file, so you can view sales history.
  • Inventory Management: Add stock quantities for each product and reduce stock whenever a sale occurs.
  • Graphical User Interface (GUI): If you're interested, learn a library like Tkinter and transform this text-based application into one with a more appealing graphical interface.

Keep practicing, experimenting, and don't be afraid to try new things. If you have any questions or encounter difficulties, feel free to ask in the comments section below. Happy coding!

Bahasa: EN ↑