0% found this document useful (0 votes)
11 views7 pages

Import Pandas As PD

The document is a Python script that manages product inventory, customer details, and sales records using pandas. It includes functions for loading and saving data from CSV files, displaying information, adding products and customers, processing sales, and generating sales reports. The script features error handling and a main loop for user interaction to perform various actions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views7 pages

Import Pandas As PD

The document is a Python script that manages product inventory, customer details, and sales records using pandas. It includes functions for loading and saving data from CSV files, displaying information, adding products and customers, processing sales, and generating sales reports. The script features error handling and a main loop for user interaction to perform various actions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

import pandas as pd

from datetime import datetime

# File paths

PRODUCTS_FILE =r'C:\Users\lenova36\Downloads\products.csv'

CUSTOMERS_FILE =r'C:\Users\lenova36\Downloads\customers.csv'

SALES_FILE =r'C:\Users\lenova36\Downloads\sales.csv'

# Read CSV files with error handling

def load_data():

try:

products = pd.read_csv(PRODUCTS_FILE)

customers = pd.read_csv(CUSTOMERS_FILE)

sales = pd.read_csv(SALES_FILE)

print("Loaded Customers Columns:", customers.columns.tolist()) # Print the column names

return products, customers, sales

except Exception as e:

print(f"Error loading data: {e}")

return pd.DataFrame(), pd.DataFrame(), pd.DataFrame()

# Save data to CSV files with error handling

def save_data(products, customers, sales):

try:

products.to_csv(PRODUCTS_FILE, index=False)

customers.to_csv(CUSTOMERS_FILE, index=False)
sales.to_csv(SALES_FILE, index=False)

except Exception as e:

print(f"Error saving data: {e}")

# Display product inventory

def display_products():

products, _, _ = load_data()

print("Product Inventory:")

print(products)

# Display customer details

def display_customers():

_, customers, _ = load_data()

print("Customer Details:")

print(customers)

# Display sales records

def display_sales():

_, _, sales = load_data()

print("Sales Records:")

print(sales)

# Add product with input validation

def add_product(name, price, stock):

if price < 0 or stock < 0:


print("Price and stock must be non-negative.")

return

products, _, _ = load_data()

new_id = products['ProductID'].max() + 1

new_product = pd.DataFrame([[new_id, name, price, stock]], columns=products.columns)

products = pd.concat([products, new_product], ignore_index=True)

save_data(products, _, _)

print(f"Product '{name}' added successfully!")

# Add a new customer

def add_customer(name, email):

_, customers, _ = load_data()

if 'CustomerID' not in customers.columns:

print("CustomerID column not found.")

return

# Create a new customer ID

new_id = customers['CustomerID'].max() + 1 if not customers.empty else 1

new_customer = pd.DataFrame([[new_id, name, email]], columns=customers.columns)

# Append the new customer to the existing DataFrame

customers = pd.concat([customers, new_customer], ignore_index=True)

# Save updated customers data

save_data(_, customers, _)
print(f"Customer '{name}' added successfully!")

# Process a sale

def process_sale(customer_id, product_id, quantity):

products, customers, sales = load_data()

if customer_id not in customers['CustomerID'].values:

print(f"Customer ID {customer_id} does not exist.")

return

if product_id not in products['ProductID'].values:

print(f"Product ID {product_id} does not exist.")

return

available_stock = products.loc[products['ProductID'] == product_id, 'Stock'].values[0]

price = products.loc[products['ProductID'] == product_id, 'Price'].values[0]

if quantity > available_stock:

print(f"Not enough stock available. Only {available_stock} items left.")

return

# Update stock

products.loc[products['ProductID'] == product_id, 'Stock'] -= quantity


# Record sale

sale_id = sales['SaleID'].max() + 1 if not sales.empty else 1

total_amount = quantity * price

new_sale = pd.DataFrame([[sale_id, customer_id, product_id, quantity, total_amount,


datetime.now().strftime('%Y-%m-%d')]], columns=sales.columns)

sales = pd.concat([sales, new_sale], ignore_index=True)

save_data(products, customers, sales)

print(f"Sale processed. SaleID: {sale_id}, Total Amount: ${total_amount:.2f}")

# Generate sales report

def generate_report():

_, _, sales = load_data()

if sales.empty:

print("No sales records available.")

return

# Ensure the Date column is in datetime format

sales['Date'] = pd.to_datetime(sales['Date'])

# Group by date and calculate total sales amount

report = sales.groupby('Date').agg({'TotalAmount': 'sum'}).reset_index()

print("Sales Report:")

print(report)
# Main loop for user interaction

def main():

while True:

display_products()

display_customers()

display_sales()

action = input("What would you like to do?


(add_product/add_customer/process_sale/generate_report/exit): ").strip().lower()

if action == 'exit':

break

if action == 'add_product':

name = input("Enter product name: ")

price = float(input("Enter product price: "))

stock = int(input("Enter product stock: "))

add_product(name, price, stock)

elif action == 'add_customer':

name = input("Enter customer name: ")

email = input("Enter customer email: ")

add_customer(name, email)
elif action == 'process_sale':

customer_id = int(input("Enter customer ID: "))

product_id = int(input("Enter product ID: "))

quantity = int(input("Enter quantity: "))

process_sale(customer_id, product_id, quantity)

elif action == 'generate_report':

generate_report()

else:

print("Invalid action. Please try again.")

if __name__ == "__main__":

main()

You might also like