Check Local Weather with Python

The objective of this application is to create a Python program that checks the local weather forecast. The application will utilize an external weather API to fetch real-time weather data based on the user’s location. The user will be prompted to enter their city, and the application will return the current weather conditions, including temperature, humidity, and a brief description of the weather.

import requests

def get_weather(city):
    api_key = 'your_api_key_here'  # Replace with your actual API key
    base_url = 'http://api.openweathermap.org/data/2.5/weather'
    
    # Construct the complete API URL
    complete_url = f"{base_url}?q={city}&appid={api_key}&units=metric"
    
    # Make a request to the OpenWeatherMap API
    response = requests.get(complete_url)
    
    # Check if the request was successful
    if response.status_code == 200:
        data = response.json()
        main = data['main']
        weather = data['weather'][0]
        
        # Extract relevant information
        temperature = main['temp']
        humidity = main['humidity']
        description = weather['description']
        
        # Display the weather information
        print(f"Weather in {city}:")
        print(f"Temperature: {temperature}°C")
        print(f"Humidity: {humidity}%")
        print(f"Description: {description.capitalize()}")
    else:
        print("City not found. Please check the name and try again.")

if __name__ == "__main__":
    city_name = input("Enter city name: ")
    get_weather(city_name)

Code Explanation

This Python application leverages the OpenWeatherMap API to fetch and display the current weather conditions for a specified city. Here’s a breakdown of the code:

  1. Importing Libraries: The requests library is imported to facilitate HTTP requests to the weather API.
  2. Function Definition: The get_weather function is defined to encapsulate the logic for fetching weather data. It takes a single parameter, city, which represents the user’s input.
  3. API Key and URL: An API key is required to authenticate requests to the OpenWeatherMap API. The base URL for the API is defined, and a complete URL is constructed using the city name and API key.
  4. Making the Request: The requests.get() method is used to send a GET request to the constructed URL. The response is checked for a successful status code (200).
  5. Parsing the Response: If the request is successful, the JSON response is parsed to extract the main weather data, including temperature, humidity, and a brief description of the weather.
  6. Displaying Results: The weather information is printed in a user-friendly format. If the city is not found, an error message is displayed.
  7. User Input: The application prompts the user to enter a city name, which is then passed to the get_weather function.

This application serves as a practical example of how to interact with web APIs in Python, providing users with real-time weather information in a straightforward manner.

Happy coding… 🙂

Leave a Reply

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