Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion Beginner_Projects/ATM Interface/ATM.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ def display_menu():
print("3. Withdraw Money")
print("4. Exit")

def account_number():
account_number=input("enter your account number:")
return account_number

def check_balance(balance):
print(f"\nYour current balance is: ${balance}")
Expand Down Expand Up @@ -44,7 +47,7 @@ def atm_interface():
balance = 5000.00 # Initial balance
while True:
display_menu()
choice = input("\nEnter your choice (1-4): ")
choice = int(input("\nEnter your choice (1-4): "))

if choice == '1':
check_balance(balance)
Expand All @@ -60,4 +63,5 @@ def atm_interface():


# Run the ATM interface
print(account_number())
atm_interface()
Comment on lines 65 to 67

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Account number input is collected but never used.

We prompt the user and immediately print the account number, but we neither persist it nor pass it into the ATM workflow. All subsequent operations still act on the hard-coded balance, so the new feature delivers no functional benefit. Please capture the value (e.g., acct = account_number()) and thread it through the session so balance/transactions are tied to that account.

🤖 Prompt for AI Agents
In Beginner_Projects/ATM Interface/ATM.py around lines 65-67, the
account_number() return value is printed but not used so the session isn't tied
to an account; assign the result to a variable (e.g., acct = account_number())
and pass that account identifier into the ATM workflow (atm_interface(acct)) and
into any functions that read/update balance or transactions; if your code
currently uses a single hard-coded balance, refactor to look up and persist
balances by account (e.g., a dict or simple storage) so all balance/transaction
operations reference the account passed in.

Original file line number Diff line number Diff line change
@@ -1,34 +1,34 @@
import requests
from bs4 import BeautifulSoup
def check_amazon_availability(product_url):
headers = {
"User-Agent": "Your User Agent Here" # Replace with a valid user agent string
}
try:
response = requests.get(product_url, headers=headers)
response.raise_for_status()
soup = BeautifulSoup(response.content, "html.parser")
title = soup.find("span", {"id": "productTitle"}).get_text(strip=True)
availability = soup.find(
"span", {"class": "a-declarative", "data-asin": True}
).get_text(strip=True)
if "out of stock" in availability.lower():
print(f"{title} is currently out of stock on Amazon.")
else:
print(f"{title} is available on Amazon.")
except requests.exceptions.HTTPError as http_err:
print(f"HTTP error occurred: {http_err}")
except requests.exceptions.RequestException as req_err:
print(f"Request error occurred: {req_err}")
if __name__ == "__main__":
product_url = "YOUR_PRODUCT_URL_HERE"
check_amazon_availability(product_url)
import requests
from bs4 import BeautifulSoup


def check_amazon_availability(product_url):
headers = {
"User-Agent": "Your User Agent Here" # Replace with a valid user agent string
}

try:
response = requests.get(product_url, headers=headers)
response.raise_for_status()
Comment on lines +11 to +12

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Add a timeout to the Amazon request.

Eliminating the timeout means a slow or stalled Amazon response will hang the script indefinitely, which is a reliability regression. Please add an explicit timeout to requests.get.

Apply this diff:

-        response = requests.get(product_url, headers=headers)
+        response = requests.get(product_url, headers=headers, timeout=10)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
response = requests.get(product_url, headers=headers)
response.raise_for_status()
response = requests.get(product_url, headers=headers, timeout=10)
response.raise_for_status()
🧰 Tools
🪛 Ruff (0.13.1)

11-11: Probable use of requests call without timeout

(S113)

🤖 Prompt for AI Agents
In Beginner_Projects/Amazon product availability checker/amazon.py around lines
11-12, the requests.get call lacks a timeout causing possible indefinite hangs;
add an explicit timeout argument (e.g., timeout=10) to requests.get and
optionally handle requests.exceptions.Timeout (or requests.RequestException) to
fail fast and surface the error instead of blocking indefinitely.


soup = BeautifulSoup(response.content, "html.parser")

title = soup.find("span", {"id": "productTitle"}).get_text(strip=True)
availability = soup.find(
"span", {"class": "a-declarative", "data-asin": True}
).get_text(strip=True)

if "out of stock" in availability.lower():
print(f"{title} is currently out of stock on Amazon.")
else:
print(f"{title} is available on Amazon.")

except requests.exceptions.HTTPError as http_err:
print(f"HTTP error occurred: {http_err}")
except requests.exceptions.RequestException as req_err:
print(f"Request error occurred: {req_err}")


if __name__ == "__main__":
product_url = "YOUR_PRODUCT_URL_HERE"
check_amazon_availability(product_url)
53 changes: 53 additions & 0 deletions Beginner_Projects/E-Commerce/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# 🛒 E-Commerce Project

## 📌 About
This is a simple **E-Commerce project** implemented in Python.
It allows users to explore a mock e-commerce system where products, customers, and orders are managed.
The project is designed for beginners who want to practice **file handling, data manipulation, data cleaning using pandas , data visualization using matplotlib and Python basics**.

---

## ⚙️ Features
- Add and view **customers**
- Add and view **products**
- Place and track **orders**
- Simple **data analysis** (like total sales, most purchased product)

---

## 🛠️ Tech Stack
- **Language:** Python
- **Libraries:**
- `pandas` → for data handling
- `matplotlib` → for visualizations

---

## 🚀 How to Run

1. Clone the repository (or download the project folder).
```bash
git clone https://github.com/UTSAVS26/PyVerse.git
```

2. Navigate to the project folder.
```bash
cd PyVerse/beginner_projects/ecommerce
```
Comment on lines +28 to +36

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Fix incorrect path in run instructions.

The listed directory (beginner_projects/ecommerce) doesn’t exist; the actual folder is Beginner_Projects/E-Commerce. Following the current steps will fail on case-sensitive systems. Please update the path so users can navigate successfully.

Apply this diff:

-    cd PyVerse/beginner_projects/ecommerce
+    cd PyVerse/Beginner_Projects/E-Commerce
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
1. Clone the repository (or download the project folder).
```bash
git clone https://github.com/UTSAVS26/PyVerse.git
```
2. Navigate to the project folder.
```bash
cd PyVerse/beginner_projects/ecommerce
```
1. Clone the repository (or download the project folder).
🤖 Prompt for AI Agents
In Beginner_Projects/E-Commerce/README.md around lines 28 to 36, the checkout
instructions reference the wrong path (git clone path is fine but the cd uses
`PyVerse/beginner_projects/ecommerce` which is incorrect and will fail on
case-sensitive systems); update the navigation command to the actual folder name
by replacing `cd PyVerse/beginner_projects/ecommerce` with `cd
PyVerse/Beginner_Projects/E-Commerce` (ensure exact casing and hyphenation) so
users can successfully change into the project directory.


3. Run the script.
```bash
python e-commerce.py
```

---

## 📚 Learning Outcomes

- File Handling (CSV/JSON)
- Data Manipulation using Pandas
- Data Visualization using Matplotlib
- Object-Oriented Programming in Python

# HARSHI GUPTA
- GSSOC'25
176 changes: 176 additions & 0 deletions Beginner_Projects/E-Commerce/e-commerce.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
import pandas as pd
import matplotlib.pyplot as plt
import datetime as date

class E_COMMERCE:
def __init__(self,customer_path="data/customers.csv", product_path="data/products.csv", order_path="data/orders.csv"):
self.customers=pd.read_csv(customer_path)
self.product=pd.read_csv(product_path)
self.orders=pd.read_csv(order_path)

def calculate_revenue(self):
self.orders['quantity'] = pd.to_numeric(self.orders['quantity'], errors="coerce")
self.product['price'] = pd.to_numeric(self.product['price'], errors="coerce")
self.orders['quantity'].fillna(self.orders['quantity'].mean(), inplace=True)
self.product['price'].fillna(self.product['price'].median(), inplace=True)
merge = pd.merge(self.product, self.orders, on='product_id', how='inner')
merge['revenue'] = merge['quantity'] * merge['price']
return merge


class DATA_CLEANING(E_COMMERCE):
def count_missing_values(self):
null_vales1=self.customers.isnull().sum()
null_values2=self.product.isnull().sum()
null_values3=self.orders.isnull().sum()
return f"{null_vales1}\n \n{null_values2} \n \n {null_values3}"

def missing_values(self):
self.product['category'].fillna(self.product['category'].value_counts().idxmax(),inplace=True)
self.orders['quantity'].fillna(self.orders['quantity'].mean(),inplace=True)
return f"{self.product} \n \n {self.orders}"

def standardize(self):
self.product['category']=self.product['category'].str.lower().str.strip()
mapping={"homeapplncs":"home appliances",
"home appliances":"home appliances",
"clothng":"clothing",
"clothing":"clothing",
"bookss":"books",
"books":"books",
"electrnics":"electronics",
"electronics":"electronics",
"sport":"sports",
"sports":"sports"
}
self.product['category']=self.product['category'].replace(mapping)
return self.product['category']

def date_time(self):
self.orders['order_date']=pd.to_datetime(self.orders['order_date'])
return self.orders['order_date']


class MERGE(E_COMMERCE):
def concat(self):
file1=pd.merge(self.orders,self.customers,on='customer_id',how='inner')
file2=pd.merge(self.product,file1,on='product_id',how='inner').head(10)
return file2


class FEATURE_ENGINEERING(E_COMMERCE):
def revenue(self):
merge=self.calculate_revenue()
return merge[['quantity','price','revenue']]

def customer_counts(self):
value=(self.orders['customer_id']).value_counts().sort_index()
return f" {value} "

def Customer_Lifetime_Value(self):
merge=self.calculate_revenue()
CLV=merge.groupby('customer_id')['revenue'].sum()
return CLV

def purchase_date(self):
self.orders['order_date'] = pd.to_datetime(self.orders['order_date'], errors='coerce')
date=self.orders.groupby('customer_id')['order_date'].agg(first_purchase='min',last_purchase='max')
return date

class ANALYSIS(E_COMMERCE):
def top_revenues(self):
merge=self.calculate_revenue()
top_10=merge.groupby('customer_id')['revenue'].sum().sort_values(ascending=False).head(10)
return top_10

def product_category_revenue(self):
merge=self.calculate_revenue()
most_revenue=merge.groupby('category')['revenue'].sum().idxmax()
revenue=merge.groupby('category')['revenue'].sum().max()
return f"the most revenue is generated by category {most_revenue} having value {revenue}"

def comparison(self):
counts=self.orders.groupby('customer_id')['order_date'].count()
compare=counts.apply(lambda x:"repeat" if x>1 else "only one")
result=compare.value_counts()
return result


class VISUALIZATION(E_COMMERCE):
def revenue_trend(self):
merge=self.calculate_revenue()
merge[['month','day','year']]=merge['order_date'].str.split("/",expand=True)
merge['month']=pd.to_numeric(merge['month'],errors="coerce")
result=merge.groupby("month")["revenue"].sum()
result.plot(kind="line",marker='*',label="revenue trend")
plt.xlabel("month")
Comment on lines +101 to +106

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

.str.split on order_date will crash after datetime conversion.

Earlier we coerce order_date to datetime64 (see DATA_CLEANING.date_time). Once that runs, calling .str.split raises AttributeError, so revenue_trend() blows up. Use the datetime accessor instead of string splitting.

Apply this diff:

-        merge[['month','day','year']]=merge['order_date'].str.split("/",expand=True)
-        merge['month']=pd.to_numeric(merge['month'],errors="coerce")
+        merge['order_date'] = pd.to_datetime(merge['order_date'], errors="coerce")
+        merge['month'] = merge['order_date'].dt.month
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
merge=self.calculate_revenue()
merge[['month','day','year']]=merge['order_date'].str.split("/",expand=True)
merge['month']=pd.to_numeric(merge['month'],errors="coerce")
result=merge.groupby("month")["revenue"].sum()
result.plot(kind="line",marker='*',label="revenue trend")
plt.xlabel("month")
merge = self.calculate_revenue()
merge['order_date'] = pd.to_datetime(merge['order_date'], errors="coerce")
merge['month'] = merge['order_date'].dt.month
result = merge.groupby("month")["revenue"].sum()
result.plot(kind="line", marker='*', label="revenue trend")
plt.xlabel("month")
🤖 Prompt for AI Agents
In Beginner_Projects/E-Commerce/e-commerce.py around lines 101 to 106, calling
.str.split on order_date will fail after earlier conversion to datetime64;
replace the string-splitting with the datetime accessor (e.g., ensure order_date
is datetime dtype and set merge['month']=merge['order_date'].dt.month), then
group by that month column and plot the revenue trend as before (no .str.split,
coerce/handle NaT if needed).

plt.ylabel("revenue")
plt.title("monthly revenue")
plt.legend()
plt.show()

def revenue_category(self):
merge=self.calculate_revenue()
trend=merge.groupby("category")["revenue"].sum()
trend.plot(kind="bar",width=0.5,label="revenue of category")
plt.xlabel("category")
plt.ylabel("revenue")
plt.title("Revenue by category")
plt.show()

def customer_type_distribution(self):
counts=self.orders.groupby("customer_id")["order_date"].count()
compare=counts.apply(lambda x:"repeat" if x>1 else "one time")
result=compare.value_counts()
plt.pie(result.values,labels=result.index,autopct="%1.1f%%",colors=['yellow','red'])
plt.title("Customer type distribution (repeat vs one-time)")
plt.show()


class EXPORT(E_COMMERCE):
def export_cleaned_csv(self, path="E_COMMERCE_CLEANED.csv"):
merged = pd.merge(self.orders, self.customers, on='customer_id', how='inner')
merged = pd.merge(merged, self.product, on='product_id', how='inner')
merged.to_csv(path, index=False)
return f"Cleaned merged dataset saved at {path}"


cleaning=DATA_CLEANING()
merge=MERGE()
features=FEATURE_ENGINEERING()
analysis=ANALYSIS()
visualization=VISUALIZATION()
export=EXPORT()

print()
print(cleaning.count_missing_values())
print()
print(cleaning.missing_values())
print()
print(cleaning.standardize())
print()
print(cleaning.date_time())
print()
print(merge.concat())
print()
print(features.revenue())
print()
print(features.customer_counts())
print()
print(features.Customer_Lifetime_Value())
print()
print(features.purchase_date())
print()
print(analysis.top_revenues())
print()
print(analysis.product_category_revenue())
print()
print(analysis.comparison())
print()
print(visualization.revenue_trend())
print()
print(visualization.revenue_category())
print()
print(visualization.customer_type_distribution())
print()
print(export.export_cleaned_csv())