Created
January 10, 2022 16:50
-
-
Save sidanand67/bbd05d6ec4f1256f849b7860e30b2856 to your computer and use it in GitHub Desktop.
Python script to check current weather of a city from a terminal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import json | |
import requests | |
import sys | |
def check_weather(city): | |
api_key = "34b68bf9f7b70bfa195f3b34c58573c1" | |
url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric" | |
data = requests.get(url).json() | |
if (data.get('cod') != 200): | |
print('City not found.') | |
print('Please check the spelling of your city.') | |
exit() | |
temp = data['main'].get('temp') | |
feels_like = data['main'].get('feels_like') | |
weather_main = data['weather'][0].get('main') | |
print(f"{city.capitalize()} has {weather_main} weather.") | |
print("Current temperature is {0:.2f}\N{DEGREE SIGN}C and it feels like {1:.2f}\N{DEGREE SIGN}C.".format( | |
temp, feels_like)) | |
if __name__ == "__main__": | |
if len(sys.argv) < 2: | |
print('City not provided.') | |
print('Usage: ./temperature <city-name>') | |
exit() | |
city = sys.argv[1] | |
check_weather(city) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment