Skip to content

Commit a944033

Browse files
committed
New small project 'product_analysis.py' as a assignment added
1 parent 8708c2c commit a944033

File tree

1 file changed

+91
-0
lines changed

1 file changed

+91
-0
lines changed

product_analysis.py

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
# 📘 Assignment 1:
2+
# Build a Script That Integrates all the topics, thet covered in '2_Python_OOP\01_Basics\Day_01_Variables_Classes\Tasks\1_data_list_processing.py'
3+
4+
# Problem Statement: Create a Python module/script that:
5+
# Reads product records from a CSV file
6+
# Filters products based on price threshold
7+
# Calculates total and average price
8+
# Saves the results to a new file (output.txt or summary.csv)
9+
# Structure your code into functions, and use try/except for errors.
10+
11+
# ✅ Save this as product_analysis.py.
12+
# ✅ Use version control: git init, git add ., git commit -m "Day 1 assignment"
13+
# ----------------------------------------------------------------------------
14+
15+
# import essential packages
16+
import csv
17+
18+
def read_product_records(file_path):
19+
"""Reading product records from file at 'file_path'"""
20+
21+
try:
22+
with open(file_path, 'r') as file:
23+
# Clean up headers by stripping whitespace & trailing commas
24+
reader = csv.DictReader(file)
25+
return [
26+
{k.strip(): v.strip()
27+
for k, v in row.items()
28+
if k is not None}
29+
for row in reader
30+
]
31+
except FileNotFoundError:
32+
print(f"Error: file {file_path} not found!\n")
33+
return [] # Return empty list to avoid crashes later
34+
35+
36+
def filter_product(items, threshold=10000):
37+
"""Key Action: Filter products where price (as float) ≤ threshold.
38+
Edge Case: Handle missing/incorrect price values."""
39+
40+
filtered = []
41+
42+
for item in items:
43+
try:
44+
if float(item.get("price", 0)) <= threshold:
45+
filtered.append(item)
46+
except (ValueError, TypeError):
47+
continue # skip invalid prices
48+
49+
return filtered
50+
51+
52+
def products_summary(products):
53+
"""Stats to Compute:
54+
Total/Average price (use sum() and len()).
55+
Max sold product (track quantity_sold).
56+
Max profit product (calculate price * quantity_sold)"""
57+
58+
if not products:
59+
return None # Handle empty data
60+
61+
prices = [float(p["price"]) for p in products]
62+
total, avg = sum(prices), sum(prices) / len(prices)
63+
64+
max_sold = max(products, key=lambda p: int(p["quantity_sold"]))
65+
max_profit = max(products, key=lambda p: float(p["price"]) * int(p["quantity_sold"]))
66+
67+
return {
68+
"total_price": total,
69+
"avg_price": avg,
70+
"max_sold": max_sold,
71+
"max_profit": max_profit
72+
}
73+
74+
75+
def save_summary(summary, output_file="./assets/summary.txt"):
76+
"""Save to output.txt (human-readable) or summary.csv (structured)."""
77+
78+
with open(output_file, 'w') as file:
79+
for key, value in summary.items():
80+
file.write(f"{key}: {value}\n") # Write each state as a line
81+
82+
print(f"\nAnalyze Data Saved Successfully!\nFile Path: '{output_file}'")
83+
print("--------------------------------\n")
84+
85+
86+
# Main workflow
87+
# Read --> Filter --> Analyze --> Save
88+
products = read_product_records("./assets/assignment_sales.csv")
89+
filtered = filter_product(products, threshold=10000)
90+
summary = products_summary(filtered)
91+
save_summary(summary, "./assets/summary.txt")

0 commit comments

Comments
 (0)