Get API Key
- Sign up at OpenWeatherMap and create an API key.
- Note the API key, as you will need it to make requests.
Step 2: Install Required Packages
You’ll need the requests
library to make API calls. You can install it using pip:
bashCopy codepip install requests
Step 3: Create the Weather Application
Create a file named weather_forecast.py
and add the following code:
pythonCopy codeimport requests
class WeatherForecast:
def __init__(self, api_key):
self.api_key = api_key
self.base_url = "http://api.openweathermap.org/data/2.5/weather"
def get_weather(self, city):
"""Fetch the weather data for the given city."""
try:
params = {
'q': city,
'appid': self.api_key,
'units': 'metric' # Change to 'imperial' for Fahrenheit
}
response = requests.get(self.base_url, params=params)
response.raise_for_status() # Raise an error for bad responses
return response.json()
except requests.exceptions.HTTPError as e:
print(f"HTTP error: {e}")
return None
except Exception as e:
print(f"Error fetching weather data: {e}")
return None
def display_weather(self, city):
"""Display the weather information."""
weather_data = self.get_weather(city)
if weather_data:
city_name = weather_data['name']
temperature = weather_data['main']['temp']
description = weather_data['weather'][0]['description']
humidity = weather_data['main']['humidity']
wind_speed = weather_data['wind']['speed']
print(f"\nWeather in {city_name}:")
print(f"Temperature: {temperature}°C")
print(f"Description: {description.capitalize()}")
print(f"Humidity: {humidity}%")
print(f"Wind Speed: {wind_speed} m/s")
else:
print("Could not retrieve weather data.")
def main():
api_key = input("Enter your OpenWeatherMap API key: ")
weather_app = WeatherForecast(api_key)
while True:
city = input("\nEnter city name (or 'quit' to exit): ")
if city.lower() == 'quit':
print("Exiting the application.")
break
weather_app.display_weather(city)
if __name__ == "__main__":
main()
Step 4: Running the Weather Application
- Open your terminal (or command prompt).
- Navigate to the directory where you saved
weather_forecast.py
. - Run the script using the command:bashCopy code
python weather_forecast.py
How It Works
- API Integration: The application fetches weather data from OpenWeatherMap using an API call based on the city name provided by the user.
- Data Display: It displays the temperature, weather description, humidity, and wind speed.
- User Input: The user can enter a city name to get the weather or type
quit
to exit.
Leave a Reply