Live Weather Dashboard in Python.
About the project: This is a project for a Live Weather Dashboard in Python. This will be a self-contained script that uses a web API to fetch and display real-time weather data for any city you choose.
This program will be a console-based application that prompts you for a city name, then connects to the OpenWeatherMap API to retrieve the current temperature, humidity, and weather conditions.
Prerequisites
- Before You Run the Code, you'll need to do two things:
- Install the requests library: Open your terminal or command prompt and run the following command to install the library needed to make API calls:
pip install requests
- Get a free API Key: Go to the OpenWeatherMap website and sign up for a free account to get a personal API key. The script requires this key to access the weather data.
This project provides a complete and interactive Live Weather Dashboard. When you run it, it will create a command-line interface where you can enter a city name to get a live weather report.
Project Level: Intermediate
You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.
Steps: Follow these stepsStep 1: Copy below code using green 'copy' button.
Step 2: Paste the code on your chosen editor.
Step 3: Save the code with filename and .py extention.
Step 4: Run (Press F5 if using python IDLE)
# live_weather_dashboard.py
import requests
import json
import os
import sys
# The base URL for the OpenWeatherMap API
API_BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
def get_api_key():
"""
Prompts the user for their OpenWeatherMap API key.
Note: In a real application, you would load this from a secure config file or environment variable.
"""
api_key = input("Enter your OpenWeatherMap API key: ").strip()
if not api_key:
print("API key cannot be empty. Exiting.")
sys.exit(1)
return api_key
def get_weather_data(city, api_key):
"""
Makes an API call to OpenWeatherMap to get weather data for a given city.
Args:
city (str): The name of the city.
api_key (str): The user's OpenWeatherMap API key.
Returns:
dict or None: A dictionary of weather data if successful, otherwise None.
"""
params = {
'q': city,
'appid': api_key,
'units': 'metric' # Use 'imperial' for Fahrenheit and miles/hour
}
try:
response = requests.get(API_BASE_URL, params=params)
response.raise_for_status() # This will raise an HTTPError for bad responses (4xx or 5xx)
return response.json()
except requests.exceptions.HTTPError as errh:
if response.status_code == 401:
print("Error: Invalid API key. Please check your key and try again.")
elif response.status_code == 404:
print(f"Error: City '{city}' not found. Please check the spelling.")
else:
print(f"HTTP Error: {errh}")
return None
except requests.exceptions.ConnectionError as errc:
print(f"Error Connecting: {errc}")
return None
except requests.exceptions.Timeout as errt:
print(f"Timeout Error: {errt}")
return None
except requests.exceptions.RequestException as err:
print(f"An unexpected error occurred: {err}")
return None
def display_weather(weather_data):
"""
Parses and displays the weather data in a user-friendly format.
Args:
weather_data (dict): The dictionary containing weather data from the API.
"""
try:
city = weather_data['name']
country = weather_data['sys']['country']
temp = weather_data['main']['temp']
feels_like = weather_data['main']['feels_like']
humidity = weather_data['main']['humidity']
wind_speed = weather_data['wind']['speed']
description = weather_data['weather'][0]['description'].capitalize()
print("\n--- Live Weather Report ---")
print(f"City: {city}, {country}")
print(f"Condition: {description}")
print(f"Temperature: {temp}°C (Feels like {feels_like}°C)")
print(f"Humidity: {humidity}%")
print(f"Wind Speed: {wind_speed} m/s")
print("---------------------------\n")
except KeyError as e:
print(f"Error: Missing data in the API response. Key '{e}' not found.")
except Exception as e:
print(f"An unexpected error occurred while parsing data: {e}")
def main():
"""
Main function to run the Weather Dashboard app.
"""
print("--- Python Live Weather Dashboard ---")
api_key = get_api_key()
while True:
city_name = input("Enter a city name ('q' to quit): ").strip()
if city_name.lower() == 'q':
print("Exiting. Goodbye!")
break
if city_name:
weather_data = get_weather_data(city_name, api_key)
if weather_data:
display_weather(weather_data)
else:
print("City name cannot be empty.")
# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
main()
← Back to Projects