Day 8 · Day 8: Libraries & APIs
Weather Application
Build a command-line weather application that fetches current weather data for a city from a public weather API using the requests library and displays it in a readable format.
Requirements
1. Use the requests library to call a weather API (e.g., OpenWeatherMap) with an API key.
2. Ask the user to enter a city name.
3. Send a GET request with the city name and API key as parameters.
4. Parse the JSON response to extract temperature, weather description, and humidity.
5. Handle errors: invalid city name (404), network errors, and missing API key.
6. Display the results in a friendly formatted output.
7. Allow the user to check weather for multiple cities in a loop.
8. Convert temperature from Kelvin to Celsius if needed (depending on API units setting).
2. Ask the user to enter a city name.
3. Send a GET request with the city name and API key as parameters.
4. Parse the JSON response to extract temperature, weather description, and humidity.
5. Handle errors: invalid city name (404), network errors, and missing API key.
6. Display the results in a friendly formatted output.
7. Allow the user to check weather for multiple cities in a loop.
8. Convert temperature from Kelvin to Celsius if needed (depending on API units setting).
import requests
API_KEY = "YOUR_API_KEY" # Get a free key from openweathermap.org
BASE_URL = "https://api.openweathermap.org/data/2.5/weather"
def get_weather(city):
params = {
"q": city,
"appid": API_KEY,
"units": "metric" # Celsius
}
try:
response = requests.get(BASE_URL, params=params, timeout=5)
if response.status_code == 404:
print(f"City '{city}' not found.")
return None
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Network error: {e}")
return None
def display_weather(data):
if not data:
return
city = data["name"]
country = data["sys"]["country"]
temp = data["main"]["temp"]
feels_like = data["main"]["feels_like"]
humidity = data["main"]["humidity"]
description = data["weather"][0]["description"].title()
print(f"\nWeather in {city}, {country}")
print(f" Condition: {description}")
print(f" Temperature: {temp}°C (feels like {feels_like}°C)")
print(f" Humidity: {humidity}%")
def main():
if API_KEY == "YOUR_API_KEY":
print("Please set a valid API_KEY before running.")
return
while True:
city = input("\nEnter a city name (or 'quit' to exit): ").strip()
if city.lower() == "quit":
print("Goodbye!")
break
if not city:
print("Please enter a city name.")
continue
data = get_weather(city)
display_weather(data)
if __name__ == "__main__":
main()
50 XP on completion
Back to Day 8
Your Code
Output
Click "Run" to execute your code...
⏳ Loading Python runtime (first run may take a few seconds)...
Log in to mark this project complete and earn XP.