-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadvanced_python_1.py
More file actions
74 lines (57 loc) · 2.89 KB
/
Copy pathadvanced_python_1.py
File metadata and controls
74 lines (57 loc) · 2.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import requests
def get_temp_humid(coordinates,weather_url):
"""
(coordinates, weather_url) -> temp , humid
Returns the temperature and humidity at given coordinates, by requesting it from given URL.
Args:
coordinates: A Tuple containing the latitude and longitude of the desired location.
weather_url: A string containing URL to request weather from (url includes required API)
Raises:
IOError: If the URL is unreachable.
KeyError: If the API passed through the URL is invalid.
"""
try:
r = requests.get(weather_url.format(coordinates[0],coordinates[1]))
json_object = r.json()
except:
raise IOError('URL is unreachable at the moment. Please check your internet connection!')
try:
temp = float(json_object['main']['temp'])
humid = float(json_object['main']['humidity'])
return temp,humid
except:
raise KeyError('Oops... your API key is invalid!')
def input_validation(coordinates):
"""
(coordinates) -> no output
Checks the validity of given coordinates.
Args:
coordinates: A Tuple containing the latitude and longitude of the desired location.
Raises:
TypeError: If the input is not of type tuple, or if elements inside tuple are not of type float.
ValueError: If the tuple does not contain exactly 2 elements, or if elements exceed allowed range.
"""
if type(coordinates) != tuple:
raise TypeError('Input must be a Tuple!')
if len(coordinates) != 2:
raise ValueError('Input Tuple must contain exactly two elements - Latitude and longitude!')
if type(coordinates[0]) != float or type(coordinates[1]) != float:
raise TypeError('Input coordinates must be of type Float!')
if coordinates[0]<-90 or coordinates[0]>90:
raise ValueError('Latitude values must be between -90 and +90')
if coordinates[1]<-180 or coordinates[1]>180:
raise ValueError('Longitude values must be between -180 and +180')
def check_weather(coordinates):
"""
(coordinates) -> no output
Prints the temperature and humidity at given coordinates.
Args:
coordinates: A Tuple containing the latitude and longitude of the desired location.
Raises:
TypeError: If the input is not of type tuple, or if elements inside tuple are not of type float.
ValueError: If the tuple does not contain exactly 2 elements, or if elements exceed allowed range.
"""
input_validation(coordinates)
weather_url = "http://api.openweathermap.org/data/2.5/weather?lat={0}&lon={1}&APPID=750f7caa81005f72c5d63d9e07af8d18&units=metric"
temp,humid = get_temp_humid(coordinates,weather_url)
print(u'Temperature is {0}\u00b0C, and humidity is {1}%'.format(temp,humid))