Weather API Program
🎯 Project: Weather API Program
Let's build a weather information program! This project combines JSON handling, error handling, and working with external data. You'll create a program that processes weather data and displays it in a user-friendly format.
This project will help you practice JSON parsing, error handling, and building practical applications that work with real-world data formats.
Project Requirements
Your weather program should:
- Parse JSON weather data
- Extract temperature, conditions, and location
- Display formatted weather information
- Handle missing or invalid data gracefully
- Provide clear error messages
- Format output nicely
Step-by-Step Implementation
Here's how to build the weather program:
weather_program.py
import json
# Sample weather data (in real app, this would come from API)
weather_json = """
{
"location": "New York",
"temperature": 72,
"condition": "Sunny",
"humidity": 65
}
"""
# Parse JSON data
try:
weather_data = json.loads(weather_json)
# Extract information
location = weather_data.get("location", "Unknown")
temp = weather_data.get("temperature", 0)
condition = weather_data.get("condition", "Unknown")
humidity = weather_data.get("humidity", 0)
# Display formatted output
print(f"Weather for {location}")
print(f"Temperature: {temp}°F")
print(f"Condition: {condition}")
print(f"Humidity: {humidity}%")
except json.JSONDecodeError:
print("Error: Invalid JSON data")
except Exception as e:
print(f"Error: {e}")
# Process multiple locations
locations_data = [
{"city": "NYC", "temp": 72},
{"city": "LA", "temp": 85}
]
for loc in locations_data:
print(f"{loc['city']}: {loc['temp']}°F")
Enhancement Ideas
Try adding these features:
- Read weather data from a file
- Save favorite locations
- Convert between Celsius and Fahrenheit
- Display weather icons based on conditions
- Calculate weather statistics
- Compare weather across multiple cities
main.py
📤 Output
Click "Run" to execute...