Python Real-Time Examples and Solutions
Scenario 1: Automating Excel Reporting
Problem: You receive a CSV file of daily sales every morning. You need to filter out cancelled orders, calculate total revenue per region, and save it as an Excel file with formatting.
Solution: Use the pandas library.
import pandas as pd
# 1. Read Data
df = pd.read_csv('daily_sales.csv')
# 2. Filter Data
# Keep only orders where Status is NOT 'Cancelled'
df_clean = df[df['Status'] != 'Cancelled']
# 3. Aggregate Data
# Group by Region and sum the Amount
report = df_clean.groupby('Region')['Amount'].sum().reset_index()
# 4. Save to Excel
report.to_excel('daily_report.xlsx', index=False)
print("Report generated successfully.")
Scenario 2: Building a High-Performance API
Problem: You need to build a microservice that serves machine learning predictions. It needs to be fast and handle concurrent requests.
Solution: Use FastAPI (modern, async).
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
@app.post("/predict/")
async def predict_price(item: Item):
# Simulate a prediction model
predicted_value = item.price * 1.1
return {"item": item.name, "predicted_price": predicted_value}
# Run with: uvicorn main:app --reload
Scenario 3: Web Scraping for Market Research
Problem: You need to track the price of a competitor's product on their website daily.
Solution: Use requests and BeautifulSoup.
import requests
from bs4 import BeautifulSoup
url = 'https://example-competitor.com/product/123'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
# Find the price element (inspect the HTML to find the class or ID)
price_element = soup.find('span', class_='product-price')
if price_element:
print(f"Current Price: {price_element.text.strip()}")
else:
print("Price not found.")