How to create a weather application with Python

Building a Weather Application with Python

To create a weather application using Python, you need libraries such as requests to send HTTP requests to the weather API and json to process the JSON data returned by the API. Below is a simple example using the OpenWeatherMap API:

Example Python Code

import requests
import json

def get_weather(city_name, api_key):
    base_url = "http://api.openweathermap.org/data/2.5/weather"
    params = {
        "q": city_name,
        "appid": api_key,
        "units": "metric"  # Celsius
    }
    response = requests.get(base_url, params=params)
    weather_data = json.loads(response.text)
    return weather_data

def main():
    city_name = input("Enter your city name: ")
    api_key = "YOUR_API_KEY"  # Replace with your OpenWeatherMap API key
    weather_data = get_weather(city_name, api_key)

    if weather_data["cod"] == 200:
        main_weather = weather_data["weather"][0]["main"]
        description = weather_data["weather"][0]["description"]
        temperature = weather_data["main"]["temp"]
        humidity = weather_data["main"]["humidity"]
        print(f"Weather in {city_name}:")
        print(f"Condition: {main_weather} - {description}")
        print(f"Temperature: {temperature} °C")
        print(f"Humidity: {humidity}%")
    else:
        print("Weather information not found for this city.")

if __name__ == "__main__":
    main()

Note: Replace YOUR_API_KEY with your API key from OpenWeatherMap. You can sign up for a free API key at OpenWeatherMap.