Hello Forum Members!
Today, using the Python programming language, I will explain step by step how to create a program that asks the user to enter a city and displays the weather!
Firstly, let's identify the tools we need to realise this project. We will need an API that provides weather data. In this example, we will use the OpenWeatherMap API. Next, we will send a request to the API using Python's requests library and process the response. Finally, we will create the user interface and display the weather information by taking the city name.
First, let's install the requests library in Python, which is required to send requests to the API.
In visual studio, you can install the required library by typing the following command via terminal or cmd:
Now, let's create the Python program step by step.
Step 1: Get the city name from the user:
Step 2: Now, with this incoming data, we will send a request to the API and process the response.
import requests
api_key = "YOUR_API_KEY" # Type your OpenWeatherMap API key here
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
response = requests.get(url)
data = response.json()
# Processing data from API
weather = data["weather"][0]["description"]
temperature = data["main"]["temp"]
Step 3: Now all that is left is to show the processed data to the user. We will print it to the console so that the user can see it.
print(f ‘Weather in {city}: {weather_status}’)
print(f ‘Temperature of {city}: {temperature} °C’)
This is what you need to do! Now you can run your Python program and find out the weather of the city you want. If you have any questions or suggestions for the code, feel free to share!
All Codes:
import requests
def main():
print("Hello, Jetto Net!")
city = input("Please write the city you want to know the weather for: ")
api_key = "YOUR_API_KEY" # Type your OpenWeatherMap API key here
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(‘Weather information was not received. Please enter a valid city name.’)
if __name__ == "__main__":
main()
Display More