Theme editor

Guide Creating a City-Specific Weather App with Python: Step-by-Step Guide

  • Thread starter Thread starter CL4Y
  • Start date Start date
  • Views 158

CL4Y

Keyboard Ninja
Administrator
Thread owner

Creating a City-Specific Weather App with Python ☀️


Today, I will walk you through creating a Python program that asks the user to enter a city name and then displays the current weather for that city.

First, let’s outline the tools we need. We will use a weather data API. In this example, we’ll use the OpenWeatherMap API. Then, using Python’s requests library, we will send a request to the API and process the response. Finally, we’ll build a simple user interface to get the city name and display the weather data.

Before we start coding, install the requests library in Python. In Visual Studio’s terminal or CMD, run:

Python:
pip install requests

Now, let's build the program step by step.

Step 1: Get City Name from User


Python:
city = input("Which city's weather would you like to check? ")

Step 2: Fetch and Process Data from API


Now, we will send a request to the API with the city name and process the response:

Python:
import requests

api_key = "YOUR_API_KEY"  # Replace with your OpenWeatherMap API key
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"

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

# Process data from API
weather = data["weather"][0]["description"]
temperature = data["main"]["temp"]

Step 3: Display the Processed Data to the User


Finally, print the weather information to the console:

Python:
print(f"Weather in {city}: {weather}")
print(f"Temperature in {city}: {temperature} °C")

---

Here is the complete program:

Python:
import requests

def main():
    print("Hello, WeatherApp!")
    city = input("Enter the city you want the weather for: ")
    api_key = "YOUR_API_KEY"  # Replace with your OpenWeatherMap API key
    url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
   
    response = requests.get(url)
    data = response.json()
   
    if data["cod"] == 200:
        weather = data["weather"][0]["description"]
        temperature = data["main"]["temp"]
        humidity = data["main"]["humidity"]
        print(f"Weather in {city}: {weather}, Temperature: {temperature}°C, Humidity: {humidity}%")
    else:
        print("Could not retrieve weather data. Please enter a valid city name.")

if __name__ == "__main__":
    main()
 
Thread owner
You can now run your Python program and find out the weather in any city you want.
 
Back
Top