Introduction
Budgeting is an essential part of managing personal finances. Keeping track of your expenses helps you understand where your money is going and plan accordingly. This tutorial will build a simple command-line budgeting program in Python. This program will allow you to add items with their prices and quantities, view the list of items, see the total amount payable, and clear all data.
You Can Access the code and run (Click here)
def List_items():
# Initialize lists to store item names, quantities, and total prices
item_list = []
quantity_list = []
total_list = []
# Function to print the bill
def print_bill():
print('_______________________')
print("Your bill is: ")
for item, quantity, total in zip(item_list, quantity_list, total_list):
print(f"{item}: Quantity={quantity}, Total={total}")
# Loop to take input from the user
while True:
item = input("Enter item name (or 'x' to exit): ")
if item.lower() == "x":
print_bill() # Print the bill when user exits
print('________________________________')
print("Total amount to be paid: ", sum(total_list))
print('________________________________')
break
else:
item_list.append(item)
# Input price with error handling for non-numeric values
while True:
try:
price = int(input("Enter price: "))
break
except ValueError:
print("Invalid input. Please enter a numeric value for the price.")
# Input quantity with error handling for non-numeric values
while True:
try:
quantity = int(input("Enter quantity: "))
break
except ValueError:
print("Invalid input. Please enter a numeric value for the quantity.")
quantity_list.append(quantity)
# Calculate total price for the current item
total = price * quantity
total_list.append(total)
print("Total: ", total)
# Append item details to a file
item_chunk = f"item name: {item}, price of single item: {price}, quantity: {quantity}, total price: {total}\n"
with open("item_list.txt", "a") as file:
file.write(item_chunk)
# Update the total price in the file
try:
with open("total_price.txt", "r") as file:
total_old = int(file.read())
except FileNotFoundError:
total_old = 0
total += total_old
with open("total_price.txt", "w") as file:
file.write(str(total))
def show_items():
# Display the items from the file
try:
with open("item_list.txt", "r") as file:
print(file.read())
except FileNotFoundError:
print("No items found. Please add items first.")
def delete_items():
while True:
auth = input("Enter Password:")
if auth == "x":
break
elif auth == "Password":
# Clear the contents of item and total price files
with open("item_list.txt", "w") as file:
file.write("")
with open("total_price.txt", "w") as file:
file.write("0")
print('_______________________')
print("Data cleared Sucessfuly.")
print('_______________________')
break
else:
print('_______________________')
print("Password is incorrect\ntype x to exit")
print('_______________________')
# Main loop for the program menu
while True:
print("Welcome to Khata, your budgeting partner!")
print("0. Clear Data \n1. List items \n2. See item list \n3. See total payable amount\n4. Exit")
choice = input("Enter your choice: ")
if choice == "1":
List_items()
elif choice == "2":
print("Item list:")
show_items()
elif choice == "3":
try:
with open("total_price.txt", "r") as file:
print("____________________\nTotal payable amount:", file.read(), "\n____________________")
except FileNotFoundError:
print("No total amount found. Please add items first.")
elif choice == "4":
print("____________________\nThank you for using Khata!\n____________________")
break
elif choice == "0":
delete_items()
else:
print("Invalid choice. Please enter a valid option.")
Step-by-Step Breakdown
- Initial Setup and Input Handling:
- We start by defining a function
List_items()that initializes three lists:item_list,quantity_list, andtotal_list. - The function contains a nested
print_bill()function that prints the list of items along with their quantities and total prices. - Inside a
whileloop, we take input from the user for item names, prices, and quantities. The loop continues until the user enters ‘x’ to exit.
- Error Handling:
- To ensure the user inputs valid numeric values for prices and quantities, we use
tryandexceptblocks to catchValueErrorexceptions and prompt the user again.
- Calculating and Storing Totals:
- For each item, we calculate the total price by multiplying the price by the quantity and append this value to the
total_list. - We also store the item details in a file called
item_list.txtfor persistent storage.
- Updating Total Amount:
- We read the existing total amount from a file called
total_price.txt. If the file doesn’t exist, we assume the total is 0. - We update the total amount by adding the current item’s total and write the new total back to the file.
- Displaying Items and Clearing Data:
- The
show_items()function reads and displays the contents ofitem_list.txt. - The
delete_items()function allows the user to clear all data by entering a password. If the password is correct, it clears the contents of bothitem_list.txtandtotal_price.txt.
- Main Menu:
- The main part of the program is a loop that displays a menu with options to list items, see the item list, see the total payable amount, clear data, or exit.
- Based on the user’s choice, the appropriate function is called.
Conclusion
This simple budgeting program demonstrates basic file handling, error checking, and user interaction in Python. This tutorial provides a foundation for building more complex budgeting tools and helps you get started with practical Python programming.
Leave a comment