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 callsfetch_weatherwith the provided city and API key.
Steps to Run the Program
- Obtain an API key from OpenWeatherMap by signing up at OpenWeatherMap.
- Replace
your_api_key_herein the code with your actual API key. - Ensure Python and the
requestslibrary are installed on your system. - Copy the code into a file named
weather_fetcher.py. - Open a terminal or command prompt and navigate to the directory containing the file.
- Run the script using the command:
python weather_fetcher.py. - Enter the name of the city when prompted to fetch its weather details.

