Weather Information Fetcher Program in Python

 

 

Introduction

Weather data is essential for planning daily activities, travel, and more. This program demonstrates how to fetch and display weather information for a specific location using an API. By leveraging the OpenWeatherMap API, this program retrieves real-time weather details like temperature, humidity, and weather conditions.

Objective

The objective of this program is to interact with a weather API, fetch data for a specified location, and present it in a readable format using Python.

Python Code

import requests

def fetch_weather(api_key, city):
    url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
    try:
        response = requests.get(url)
        response.raise_for_status()
        data = response.json()

        print("Weather Information:")
        print(f"City: {data['name']}")
        print(f"Temperature: {data['main']['temp']}°C")
        print(f"Weather: {data['weather'][0]['description']}")
        print(f"Humidity: {data['main']['humidity']}%")
    except requests.exceptions.HTTPError as http_err:
        print(f"HTTP error occurred: {http_err}")
    except Exception as err:
        print(f"An error occurred: {err}")

def main():
    api_key = "your_api_key_here"  # Replace with your OpenWeatherMap API key
    city = input("Enter the city name: ")
    fetch_weather(api_key, city)

if __name__ == "__main__":
    main()

Program Explanation

This Python program fetches and displays weather information. Here’s a breakdown of the program structure:

  • fetch_weather: Sends a request to the OpenWeatherMap API and processes the response to extract and display weather data.
  • main: Handles user input for the city name and calls fetch_weather with the provided city and API key.

Steps to Run the Program

  1. Obtain an API key from OpenWeatherMap by signing up at OpenWeatherMap.
  2. Replace your_api_key_here in the code with your actual API key.
  3. Ensure Python and the requests library are installed on your system.
  4. Copy the code into a file named weather_fetcher.py.
  5. Open a terminal or command prompt and navigate to the directory containing the file.
  6. Run the script using the command: python weather_fetcher.py.
  7. Enter the name of the city when prompted to fetch its weather details.
© 2024 Learn Programming. All Rights Reserved.

 

Leave a Reply

Your email address will not be published. Required fields are marked *