Categories: Python
Tags:

Here’s a simple weather app in Python using the OpenWeatherMap API. You’ll need to sign up at OpenWeatherMap to get a free API key.

Steps:

  1. Install the requests module if you haven’t already: pip install requests
  2. Replace "YOUR_API_KEY" with your actual OpenWeatherMap API key in the script below.

Python Weather App

import requests

def get_weather(city):
    API_KEY = "YOUR_API_KEY"  # Replace with your OpenWeatherMap API key
    BASE_URL = "https://api.openweathermap.org/data/2.5/weather"
    
    params = {"q": city, "appid": API_KEY, "units": "metric"}  # Use "imperial" for Fahrenheit
    response = requests.get(BASE_URL, params=params)
    
    if response.status_code == 200:
        data = response.json()
        weather = {
            "City": data["name"],
            "Temperature": data["main"]["temp"],
            "Weather": data["weather"][0]["description"],
            "Humidity": data["main"]["humidity"],
            "Wind Speed": data["wind"]["speed"],
        }
        return weather
    else:
        return {"Error": "City not found or invalid API key"}

if __name__ == "__main__":
    city = input("Enter city name: ")
    weather_data = get_weather(city)
    
    if "Error" in weather_data:
        print(weather_data["Error"])
    else:
        print(f"Weather in {weather_data['City']}:")
        print(f"Temperature: {weather_data['Temperature']}°C")
        print(f"Condition: {weather_data['Weather']}")
        print(f"Humidity: {weather_data['Humidity']}%")
        print(f"Wind Speed: {weather_data['Wind Speed']} m/s")

Features:

✅ Fetches real-time weather using OpenWeatherMap
✅ Displays temperature, weather condition, humidity, and wind speed
✅ Error handling for incorrect city names