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:
- Importing Libraries: The
requests
library is imported to facilitate HTTP requests to the weather API. - 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. - 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.
- 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). - 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.
- Displaying Results: The weather information is printed in a user-friendly format. If the city is not found, an error message is displayed.
- 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… 🙂
I’ve been designing web applications—on and off—since 2001, back when animated GIFs were all the rage and ‘responsive design’ meant answering your client’s emails. Over the past 14 years, I’ve kept pace with the ever-evolving trends in PHP development, successfully delivering a variety of projects that made my clients happy (and kept me caffeinated).
This website serves as my soapbox—a place to share the insights I’ve picked up along the way with anyone curious enough to dive in. Welcome aboard!
Need some custom work done? Or, just want to reach out? Email: dan@danoriordan.com