Skip to content

Commit b27abc1

Browse files
Update weather-app.py
1 parent b5287db commit b27abc1

File tree

1 file changed

+39
-8
lines changed

1 file changed

+39
-8
lines changed

weather-app.py

Lines changed: 39 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,51 @@
11
import requests
22

33
def get_temperature(city_name, api_key):
4+
"""
5+
Fetches the current temperature in Fahrenheit for a given U.S. city
6+
using the OpenWeatherMap API.
7+
8+
Parameters:
9+
city_name (str): The name of the U.S. city.
10+
api_key (str): Your OpenWeatherMap API key.
11+
12+
Returns:
13+
float: Current temperature in Fahrenheit if successful.
14+
None: If an error occurs or the data cannot be retrieved.
15+
"""
16+
if not api_key or not isinstance(api_key, str):
17+
print("Error: Invalid or missing API key.")
18+
return None
19+
420
base_url = "https://api.openweathermap.org/data/2.5/weather"
521
params = {
622
'q': f"{city_name},US",
723
'appid': api_key,
8-
'units': 'imperial' # Fahrenheit
24+
'units': 'imperial'
925
}
10-
response = requests.get(base_url, params=params)
11-
12-
if response.status_code == 200:
26+
27+
try:
28+
response = requests.get(base_url, params=params, timeout=10)
29+
response.raise_for_status()
1330
data = response.json()
14-
temp = data['main']['temp']
15-
return temp
16-
else:
17-
return None
31+
32+
if 'main' in data and 'temp' in data['main']:
33+
return data['main']['temp']
34+
else:
35+
print("Error: Unexpected response structure.")
36+
return None
37+
except requests.exceptions.HTTPError as http_err:
38+
print(f"HTTP error occurred: {http_err} - {response.text}")
39+
except requests.exceptions.ConnectionError:
40+
print("Error: Network connection error.")
41+
except requests.exceptions.Timeout:
42+
print("Error: The request timed out.")
43+
except requests.exceptions.RequestException as err:
44+
print(f"Error: An unexpected error occurred: {err}")
45+
except ValueError:
46+
print("Error: Failed to parse JSON response.")
47+
48+
return None
1849

1950
def main():
2051
import os

0 commit comments

Comments
 (0)