Skip to main content

Featured

Python code for " Guessing Game ". Computer science project

Python Code for " Weather app" using " OpenWeatherMap " API. Computer Science project

 HERE'S A PYTHON CODE FOR WEATHER APP USING THE OpenWeatherMap API:

SOURCE CODE-

import requests
import json

API_KEY = 'your_api_key' # replace with your actual API key


def get_weather(city):
# Make a request to the OpenWeatherMap API
url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}'
response = requests.get(url)

# Check if the response is successful
if response.status_code == 200:
# Parse the JSON data
data = json.loads(response.text)

# Extract the relevant weather information
description = data['weather'][0]['description']
temperature = data['main']['temp'] - 273.15 # convert from Kelvin to Celsius
humidity = data['main']['humidity']

# Return a formatted string with the weather information
return f'The weather in {city} is {description}, with a temperature of {temperature:.1f}°C and a humidity of {humidity}%.'
else:
return 'Error: Unable to retrieve weather data.'


if __name__ == '__main__':
city = input('Enter a city: ')
weather = get_weather(city)
print(weather)

Comments