|
| 1 | +import requests |
| 2 | +import json |
| 3 | +import time |
| 4 | + |
| 5 | +API_KEY = '7e3f21edee540e6110af347b55eb1ab2' |
| 6 | +UNIT = 'metric' |
| 7 | +BASE_URL = 'https://api.openweathermap.org/data/2.5/find' |
| 8 | + |
| 9 | +def fetch_weather(city): |
| 10 | + try: |
| 11 | + url = f"{BASE_URL}?q={city}&appid={API_KEY}&units={UNIT}" |
| 12 | + response = requests.get(url) |
| 13 | + if response.status_code == 200: |
| 14 | + return response.json() |
| 15 | + else: |
| 16 | + print(f"Error fetching data: {response.status_code}") |
| 17 | + return None |
| 18 | + except Exception as e: |
| 19 | + print(f"An error occurred: {e}") |
| 20 | + return None |
| 21 | + |
| 22 | +def check_alerts(data, temp_threshold, wind_speed_threshold): |
| 23 | + if not data or 'list' not in data or not data['list']: |
| 24 | + print("No data available to check alerts.") |
| 25 | + return |
| 26 | + |
| 27 | + weather_info = data['list'][0] |
| 28 | + temp = weather_info['main']['temp'] |
| 29 | + wind_speed = weather_info['wind']['speed'] |
| 30 | + |
| 31 | + alerts = [] |
| 32 | + if temp > temp_threshold: |
| 33 | + alerts.append(f"Temperature alert! Current temperature: {temp}°C") |
| 34 | + if wind_speed > wind_speed_threshold: |
| 35 | + alerts.append(f"Wind speed alert! Current wind speed: {wind_speed} m/s") |
| 36 | + |
| 37 | + if alerts: |
| 38 | + print("\n".join(alerts)) |
| 39 | + else: |
| 40 | + print("No alerts. Weather conditions are normal.") |
| 41 | + |
| 42 | +def main(): |
| 43 | + city = input("Enter city name: ") |
| 44 | + temp_threshold = float(input("Enter temperature threshold (°C): ")) |
| 45 | + wind_speed_threshold = float(input("Enter wind speed threshold (m/s): ")) |
| 46 | + |
| 47 | + while True: |
| 48 | + weather_data = fetch_weather(city) |
| 49 | + check_alerts(weather_data, temp_threshold, wind_speed_threshold) |
| 50 | + print("Waiting for the next check...") |
| 51 | + # check every hour |
| 52 | + time.sleep(3600) |
| 53 | +if __name__ == "__main__": |
| 54 | + main() |
0 commit comments