Python Assignment-2
Course:Python for Data Science
Academic Year:2025-2026
Name:C V Aswitha
Register Number:2117250070037
Department & Section:AI&DS-A
Email ID:aswitha.250037@[Link]
1
[Link] TITLE:
‘Weather Data Storage’
2. PROBLEM STATEMENT:
In many applications, weather data such as temperature,
humidity, and conditions for various cities needs to be collected, stored,
and retrieved efficiently. Manually tracking this data can be error-prone
and time-consuming. This project aims to create a simple Python
program that allows users to input weather data for multiple cities, store
it in a structured format like a CSV file, and retrieve or display the
stored data on demand. This solves the issue of basic data management
for weather information in a beginner-friendly way.
3. OBJECTIVE:
To collect weather data inputs from the user for
different cities.
To store the collected data persistently in a file for
future access
To retrieve and display the stored weather data when
requested.
4. TOOLS & TECHNOLOGY USED:
Python Version: 3.15
IDE Used: Jupyter Notebook
2
5. METHODOLOGY/APPROACH:
Import necessary libraries such as csv for file
handling.
Prompt the user to input weather data (city,
temperature, humidity, condition).
Store the input data in a CSV file, appending new
entries if the file exists.
Provide an option to retrieve and display all stored
data from the file.
6. PROGRAM CODE:
import csv
import os
import sys
import pandas as pd
import [Link] as plt
from datetime import datetime
from colorama import init, Fore, Style
import warnings
# Suppress pandas warnings (openpyxl / future deprecation)
[Link]("ignore", category=FutureWarning)
# Initialize colorama
init(autoreset=True)
CSV_FILE = "weather_records.csv"
EXCEL_FILE = "weather_report.xlsx"
HEADER = ["City", "Date", "Temperature_C", "Humidity_%"]
def clear_screen():
[Link]('cls' if [Link] == 'nt' else 'clear')
3
def print_header():
print(f"\n{[Link]}{[Link]}╔════════════
════════════════════════════════════
════╗")
print( "║ Weather Data Manager v3.1 ║")
print( "╚═══════════════════════════════
═════════════════════╝")
print(f"{Fore.LIGHTBLACK_EX}Track • Analyze •
Visualize weather data\n")
def initialize_files():
if not [Link](CSV_FILE):
with open(CSV_FILE, 'w', newline='', encoding='utf-8') as f:
writer = [Link](f)
[Link](HEADER)
print(f"{[Link]}✓ Created database: {CSV_FILE}")
def load_data():
if not [Link](CSV_FILE):
return [Link](columns=HEADER)
try:
df = pd.read_csv(CSV_FILE)
df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
df = [Link](subset=['Date']) # drop rows with invalid
dates
return df
except Exception as e:
print(f"{[Link]}Error reading CSV file: {e}")
return [Link](columns=HEADER)
4
def save_data(df):
try:
df.to_csv(CSV_FILE, index=False)
except Exception as e:
print(f"{[Link]}Error saving data: {e}")
def get_valid_choice(prompt, min_val, max_val):
while True:
try:
val = int(input(prompt))
if min_val <= val <= max_val:
return val
print(f"{[Link]}Please enter a number between
{min_val} and {max_val}")
except ValueError:
print(f"{[Link]}Invalid input. Please enter a number.")
def add_weather_data():
clear_screen()
print_header()
print(f"{[Link]}→ Add New Record\n")
city = input(f"{[Link]}City name : ").strip()
if not city:
print(f"{[Link]}City cannot be empty!")
return
date_str = input(f"{[Link]}Date (YYYY-MM-DD) :
").strip()
try:
date = [Link](date_str, "%Y-%m-%d")
except ValueError:
5
print(f"{[Link]}Invalid date format! Use YYYY-MM-
DD")
return
try:
temp = float(input(f"{[Link]}Temperature (°C) : "))
if not -60 <= temp <= 60:
print(f"{[Link]}Temperature seems unrealistic (-60
to 60 °C allowed).")
return
except ValueError:
print(f"{[Link]}Temperature must be a number.")
return
try:
hum = float(input(f"{[Link]}Humidity (%) : "))
if not 0 <= hum <= 100:
print(f"{[Link]}Humidity must be between 0 and
100%.")
return
except ValueError:
print(f"{[Link]}Humidity must be a number.")
return
new_row = [Link]({
"City": [[Link]()],
"Date": [date],
"Temperature_C": [round(temp, 1)],
"Humidity_%": [round(hum, 1)]
})
df = load_data()
df = [Link]([df, new_row], ignore_index=True)
6
save_data(df)
print(f"\n{[Link]}✓ Record added successfully!")
def view_data(city_filter=None):
clear_screen()
print_header()
df = load_data()
if [Link]:
print(f"{[Link]}No records yet.")
return df
if city_filter:
df = df[df['City'].[Link]() == city_filter.lower()]
if [Link]:
print(f"{[Link]}No records found for city:
{city_filter.title()}")
return df
title = f"Records for {city_filter.title()}"
else:
title = "All Records"
print(f"{[Link]}{title} ({len(df)} records)")
print(f"{'#':<4} {'City':<18} {'Date':<12} {'Temp(°C)':<10}
{'Hum(%)':<8}")
print("-" * 60)
for i, row in [Link]():
print(f"{i+1:<4} {row['City']:<18}
{row['Date'].strftime('%Y-%m-%d'):<12} "
7
f"{row['Temperature_C']:<10.1f}
{row['Humidity_%']:<8.1f}")
return df
def delete_record():
clear_screen()
print_header()
print(f"{[Link]}→ Delete Record\n")
df = view_data()
if [Link]:
print(f"\n{[Link]}No records available to delete.")
return
total = len(df)
idx = get_valid_choice(f"\n{[Link]}Enter record
number to delete (1–{total}) → ", 1, total) - 1
record = [Link][idx]
confirm = input(f"{[Link]}Delete {record['City']} -
{record['Date'].date()}? (y/n): ").lower()
if confirm in ('y', 'yes'):
df = [Link](idx).reset_index(drop=True)
save_data(df)
print(f"{[Link]}✓ Record deleted.")
else:
print(f"{[Link]}Delete cancelled.")
def show_statistics():clear_screen()
print_header()
8
print(f"{[Link]}→ Statistics\n")
df = load_data()
if [Link]:
print(f"{[Link]}No data available.")
return
print(f"{[Link]}Overall Statistics:")
print("-" * 40)
print(f"Total records : {len(df)}")
print(f"Date range : {df['Date'].min().date()} →
{df['Date'].max().date()}")
print(f"Avg Temperature :
{df['Temperature_C'].mean():.1f} °C")
print(f"Min / Max Temp : {df['Temperature_C'].min():.1f}
→ {df['Temperature_C'].max():.1f} °C")
print(f"Avg Humidity : {df['Humidity_%'].mean():.1f} %")
print(f"Min / Max Humidity: {df['Humidity_%'].min():.1f} →
{df['Humidity_%'].max():.1f} %\n")
if len(df['City'].unique()) > 1:
print(f"{[Link]}Per City Statistics:")
print("-" * 40)
stats = [Link]('City').agg({
'Temperature_C': ['mean', 'min', 'max', 'count'],
'Humidity_%': ['mean', 'min', 'max']
}).round(1)
[Link] = ['Avg_Temp', 'Min_Temp', 'Max_Temp',
'Records', 'Avg_Hum', 'Min_Hum', 'Max_Hum']
print(stats)
9
def export_to_excel():
clear_screen()
print_header()
print(f"{[Link]}→ Export to Excel\n")
df = load_data()
if [Link]:
print(f"{[Link]}Nothing to export.")
return
try:
export_df = [Link]()
export_df['Date'] = export_df['Date'].[Link]('%Y-%m-
%d')
export_df.to_excel(EXCEL_FILE, index=False,
sheet_name="Weather Data")
print(f"{[Link]}✓ Exported successfully to:
{EXCEL_FILE}")
except Exception as e:
print(f"{[Link]}Export failed: {e}")
def view_graphs(city_filter=None):
clear_screen()
print_header()
df = load_data()
if [Link]:
print(f"{[Link]}No data to plot.")
return
if city_filter:
df = df[df['City'].[Link]() == city_filter.lower()]
if [Link]:
10
print(f"{[Link]}No data for city: {city_filter}")
return
title_suffix = f" - {city_filter.title()}"
else:
title_suffix = ""
df = df.sort_values('Date')
[Link]('seaborn-v0_8-darkgrid')
# Temperature plot
[Link](figsize=(12, 6))
if not city_filter:
for city, group in [Link]('City'):
[Link](group['Date'], group['Temperature_C'],
marker='o', linewidth=2, markersize=6, label=city)
else:
[Link](df['Date'], df['Temperature_C'], marker='o',
linewidth=2, markersize=8, color='#e74c3c')
[Link](f"Temperature Trend{title_suffix}", fontsize=16,
fontweight='bold')
[Link]("Date", fontsize=12)
[Link]("Temperature (°C)", fontsize=12)
[Link](rotation=45)
[Link]()
plt.tight_layout()
[Link]()
# Humidity plot
[Link](figsize=(12, 6))
if not city_filter:
11
for city, group in [Link]('City'):
[Link](group['Date'], group['Humidity_%'], marker='s',
linewidth=2, markersize=6, label=city)
else:
[Link](df['Date'], df['Humidity_%'], marker='s',
linewidth=2, markersize=8, color='#3498db')
[Link](f"Humidity Trend{title_suffix}", fontsize=16,
fontweight='bold')
[Link]("Date", fontsize=12)
[Link]("Humidity (%)", fontsize=12)
[Link](rotation=45)
[Link]()
plt.tight_layout()
[Link]()
print(f"{[Link]}✓ Graphs displayed.")
12
7. OUTPUT:
13
14
15
8. RESULT:
The project successfully allows users to input weather
data for cities, stores it in a CSV file for persistence, and
retrieves the data to display it. The system handles multiple
entries and ensures data is not lost between runs, providing a
basic yet functional weather data storage solution.
[Link]:
Through this project, I learned how to handle user
inputs in Python and use the csv module for file operations. I
gained experience in structuring a simple menu-driven program
and managing data persistence. It also helped me understand
error handling basics, like checking if a file exists. Overall, it
reinforced my knowledge of data manipulation in a data science
context.
10. FUTURE ENHANCEMENT:
This project can be improved by integrating a
real-time weather API (e.g., OpenWeatherMap) to fetch actual
data instead of manual input. Adding a database like SQL for
better scalability, implementing data visualization with
matplotlib (e.g., temperature charts), or creating a web interface
using Flask could enhance it further.
16
17
18