Weather forecast software

 Here's the source code of weather forecast software:πŸ‘‡ 


import requests
API_KEY = 'your_openweathermap_api_key'
BASE_URL = "http://api.openweathermap.org/data/2.5/weather?"
FORECAST_URL = "http://api.openweathermap.org/data/2.5/forecast?"

def get_weather(city):
    # Construct the complete API call URL
    url = BASE_URL + "q=" + city + "&appid=" + API_KEY + "&units=metric"
    response = requests.get(url)
    return response.json()

def get_forecast(city):
    url = FORECAST_URL + "q=" + city + "&appid=" + API_KEY + "&units=metric"
    response = requests.get(url)
    return response.json()

def display_weather(data):
    if data["cod"] != "404":
        main = data["main"]
        weather = data["weather"][0]
        print(f"City: {data['name']}")
        print(f"Temperature: {main['temp']}°C")
        print(f"Weather: {weather['description']}")
        print(f"Humidity: {main['humidity']}%")
        print(f"Pressure: {main['pressure']} hPa")
    else:
        print("City not found!")

def display_forecast(data):
    if data["cod"] != "404":
        for forecast in data['list'][:5]:  # Displaying only the first 5 forecasts (for simplicity)
            main = forecast["main"]
            weather = forecast["weather"][0]
            print(f"Date: {forecast['dt_txt']}")
            print(f"Temperature: {main['temp']}°C")
            print(f"Weather: {weather['description']}")
            print("------")
    else:
        print("City not found!")

if __name__ == "__main__":
    city = input("Enter city name: ")
    print("Current Weather:")
    weather_data = get_weather(city)
    display_weather(weather_data)
   
    print("\n5-Day Forecast:")
    forecast_data = get_forecast(city)
    display_forecast(forecast_data)


Here's the sample output:πŸ‘‡

Enter city name: London
Current Weather:
City: London
Temperature: 15.0°C
Weather: clear sky
Humidity: 72%
Pressure: 1012 hPa

5-Day Forecast:
Date: 2024-08-21 12:00:00
Temperature: 17.3°C
Weather: light rain
------
Date: 2024-08-21 15:00:00
Temperature: 17.8°C
Weather: light rain
------
...

Comments