Created
January 7, 2020 20:00
-
-
Save Amber-Cloud/30d2e771cfde33db04df5057c3369f6d to your computer and use it in GitHub Desktop.
A program that gives current weather for a given city name (with ALPHA-2 country code).
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
import urllib | |
import json | |
def kelvin_to_celsius(temp): | |
''' | |
This function transforms temperature in Kelvins to Celsius | |
''' | |
return round(temp - 273.15) | |
def weather_search(): | |
''' | |
This function requests info from API for data provided by the user and outputs the current weather | |
''' | |
api_key = 'put your api id here' | |
# you can get it for free by registering here: https://home.openweathermap.org/users/sign_up | |
city_name = input('Please enter the city name: ') | |
country = input('Please enter the country code (two letters): ') | |
city_country = city_name + ',' + country | |
query_params = {'APPID': api_key, 'q': city_country} | |
encoded_params = urllib.parse.urlencode(query_params) | |
final_link = 'http://api.openweathermap.org/data/2.5/weather?' + encoded_params | |
try: | |
url_open_in_json = urllib.request.urlopen(final_link) | |
except urllib.error.URLError as e: | |
print(e.reason) | |
except urllib.error.HTTPError as e: | |
print(e.reason) | |
else: | |
data = json.load(url_open_in_json) | |
temp = kelvin_to_celsius(data["main"]["temp"]) | |
feels_like = kelvin_to_celsius(data["main"]['feels_like']) | |
sky = data["weather"][0]["main"] | |
print(f"The weather in {city_country} is {sky}, the temperature (C) is {temp} (feels like {feels_like}).") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment