Simple Cashier Program With Python

by Alex Braham 35 views

Hey guys! Ever wanted to create your own cashier program using Python? It's simpler than you might think! In this article, we're going to walk through building a basic cashier program step-by-step. So, grab your favorite text editor, and let's dive in!

What You'll Learn

  • Setting up the basic structure of a Python program.
  • Taking user input for items and prices.
  • Calculating totals and applying discounts.
  • Handling payments and generating receipts.

Prerequisites

Before we start, make sure you have Python installed on your system. You can download the latest version from the official Python website. You should also have a basic understanding of Python syntax, variables, and control structures.

Setting Up the Program

First, let's set up the basic structure of our program. We'll start by creating a new Python file and adding some initial comments to describe what the program does.

Creating the Python File

Create a new file named cashier.py. This will be the main file for our program. Open it in your favorite text editor or IDE.

Adding Initial Comments

Add some comments at the beginning of the file to describe the program. This helps others (and yourself) understand what the code is for.

# This is a simple cashier program written in Python
# Author: Your Name
# Date: Current Date

Defining the Main Function

It's good practice to define a main function where the main logic of the program resides. This helps in organizing the code and makes it more readable.

def main():
    print("Welcome to the Simple Cashier Program!")

if __name__ == "__main__":
    main()

In this snippet, we define a main function that prints a welcome message. The if __name__ == "__main__": line ensures that the main function is called when the script is executed.

Taking User Input

Now, let's take user input for the items and prices. We'll use a loop to continuously ask for items until the user is done. Let's break this down:

Setting up Variables

We need a way to store the items and their prices. We can use a dictionary for this, where the item name is the key and the price is the value. We also need a variable to keep track of the total cost.

items = {}
total_cost = 0.0

Creating the Input Loop

We'll use a while loop to continuously ask the user for items. The loop will continue until the user enters a specific command to stop (e.g., 'done').

while True:
    item_name = input("Enter item name (or 'done' to finish): ")
    if item_name.lower() == 'done':
        break
    try:
        item_price = float(input("Enter item price: "))
        items[item_name] = item_price
        total_cost += item_price
    except ValueError:
        print("Invalid price. Please enter a number.")

In this loop, we ask the user for the item name. If the user enters 'done', we break out of the loop. Otherwise, we ask for the item price and add the item and its price to the items dictionary. We also update the total_cost.

Displaying the Items

Let's add a part to display the items and prices that the user has entered. After the loop finishes, we can print out the items and their prices.

print("\n--- Items Purchased ---")
for item, price in items.items():
    print(f"{item}: ${price:.2f}")
print(f"\nTotal Cost: ${total_cost:.2f}")

This code iterates through the items dictionary and prints each item and its price, formatted to two decimal places. It also prints the total cost.

Calculating Totals and Applying Discounts

Next, let's calculate the total cost and apply any discounts. We'll add a function to calculate the discount based on the total cost.

Calculating the Discount

We can define a function to calculate the discount. For example, let's say we offer a 10% discount if the total cost is over $50.

def calculate_discount(total):
    if total > 50:
        discount = total * 0.10
        return discount
    else:
        return 0

Applying the Discount

Now, let's apply the discount to the total cost.

discount = calculate_discount(total_cost)
final_cost = total_cost - discount

print(f"Discount Applied: ${discount:.2f}")
print(f"Final Cost: ${final_cost:.2f}")

This code calls the calculate_discount function, applies the discount to the total_cost, and prints the discount amount and the final cost.

Handling Payments and Generating Receipts

Finally, let's handle payments and generate a receipt. We'll ask the user for the payment amount and calculate the change.

Taking Payment Input

We'll ask the user for the payment amount and validate that it's a valid number.

while True:
    try:
        payment = float(input("Enter payment amount: "))
        if payment < final_cost:
            print("Insufficient payment. Please enter a higher amount.")
        else:
            break
    except ValueError:
        print("Invalid payment amount. Please enter a number.")

Calculating Change

Now, let's calculate the change.

change = payment - final_cost
print(f"Change: ${change:.2f}")

Generating Receipt

Let's generate a simple receipt. We'll print out the items, their prices, the total cost, the discount, the final cost, the payment amount, and the change.

print("\n--- Receipt ---")
for item, price in items.items():
    print(f"{item}: ${price:.2f}")
print(f"Total Cost: ${total_cost:.2f}")
print(f"Discount: ${discount:.2f}")
print(f"Final Cost: ${final_cost:.2f}")
print(f"Payment: ${payment:.2f}")
print(f"Change: ${change:.2f}")
print("\nThank you for your purchase!")

Complete Code

Here's the complete code for the simple cashier program:

def calculate_discount(total):
    if total > 50:
        discount = total * 0.10
        return discount
    else:
        return 0

def main():
    print("Welcome to the Simple Cashier Program!")

    items = {}
    total_cost = 0.0

    while True:
        item_name = input("Enter item name (or 'done' to finish): ")
        if item_name.lower() == 'done':
            break
        try:
            item_price = float(input("Enter item price: "))
            items[item_name] = item_price
            total_cost += item_price
        except ValueError:
            print("Invalid price. Please enter a number.")

    print("\n--- Items Purchased ---")
    for item, price in items.items():
        print(f"{item}: ${price:.2f}")
    print(f"\nTotal Cost: ${total_cost:.2f}")

    discount = calculate_discount(total_cost)
    final_cost = total_cost - discount

    print(f"Discount Applied: ${discount:.2f}")
    print(f"Final Cost: ${final_cost:.2f}")

    while True:
        try:
            payment = float(input("Enter payment amount: "))
            if payment < final_cost:
                print("Insufficient payment. Please enter a higher amount.")
            else:
                break
        except ValueError:
            print("Invalid payment amount. Please enter a number.")

    change = payment - final_cost
    print(f"Change: ${change:.2f}")

    print("\n--- Receipt ---")
    for item, price in items.items():
        print(f"{item}: ${price:.2f}")
    print(f"Total Cost: ${total_cost:.2f}")
    print(f"Discount: ${discount:.2f}")
    print(f"Final Cost: ${final_cost:.2f}")
    print(f"Payment: ${payment:.2f}")
    print(f"Change: ${change:.2f}")
    print("\nThank you for your purchase!")

if __name__ == "__main__":
    main()

Running the Program

To run the program, save the code in a file named cashier.py and execute it from the command line using the following command:

python cashier.py

You can try typing a few items along with prices, then when you are done you just need to type done to finish the process. Have fun!

Conclusion

And there you have it! You've created a simple cashier program using Python. This is just the beginning, though. You can add more features like inventory management, user authentication, and more sophisticated discount schemes. Keep experimenting and happy coding!