WEATHER_APP in Python – Fetch Real-Time Weather Data

INTRODUCTION

The WEATHER_APP in Python is a simple application that fetches actual-time weather records the use of an API. It permits customers to enter a city name and get contemporary weather details inclusive of temperature, humidity, and weather conditions. This mission enables in information API integration and operating with JSON statistics in Python.

STEP 1: Import the Required Module

The requests module is imported to send HTTP requests to the OpenWeatherMap API. This module allows the program to communicate with the web and fetch data

import requests

STEP 2: Define the API Key

The API key’s required for authentication to get entry to OpenWeatherMap’s weather information.

api_key = "your_api_key"

STEP 3 : Take User Input for the City Name

The program asks the user to enter a city name and stores it in the city variable.

city = input("Enter city name: ")

STEP 4: Construct the API URL

The program dynamically creates the API URL using the city name, API key, and units=metric to ensure the temperature is in Celsius.

url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"

STEP 5: Fetch Data from the API

The program sends a GET request to the API and converts the response into a JSON object.

response = requests.get(url)
data = response.json()

STEP 6: Check if the Request Was Successful

The program checks the status code (cod), where two hundred approach success, and 404 way the city changed into now not discovered.

if data["cod"] == 200:

STEP 7: Extract Relevant Weather Details

If a success, the program retrieves temperature, humidity, and climate circumstance from the JSON response.

temperature = data["main"]["temp"]
humidity = data["main"]["humidity"]
weather_condition = data["weather"][0]["description"]

STEP 8: Display the Weather Information

The program displays the weather info in a user-friendly format, with the condition text capitalized for clarity.

print(f"Weather in {city}:")
print(f"Temperature: {temperature}°C")
print(f"Humidity: {humidity}%")
print(f"Condition: {weather_condition.capitalize()}")

STEP 9: Handle Errors (Invalid City Name)

If the town isn’t found, the program shows an error message to inform the user to enter a valid town name.

else:
    print("City not found! Please enter a valid city name.")

Leave a Comment

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

Scroll to Top