0
点赞
收藏
分享

微信扫一扫

Python开发实例(十二)天气预报应用:通过API获取天气数据,让用户输入城市并显示天气情况

在这个实例中,我们将创建一个天气预报应用,使用Python的requests库来获取天气数据,并让用户输入城市名来显示该城市的天气情况。

首先,你需要申请一个天气数据的API密钥。在这个示例中,我们将使用OpenWeatherMap提供的API,你可以在 https://openweathermap.org/ 上注册并获取免费的API密钥。

请确保你已经安装了requests库。如果没有安装,可以通过以下命令来安装:

pip install requests

下面是天气预报应用的Python程序:

import requests

def get_weather_data(api_key, city):
    base_url = "http://api.openweathermap.org/data/2.5/weather"
    params = {
        "q": city,
        "appid": api_key,
        "units": "metric"  # 使用摄氏度显示温度
    }

    try:
        response = requests.get(base_url, params=params)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"天气数据获取失败: {e}")
        return None

def display_weather_data(weather_data, city):
    if "main" in weather_data and "temp" in weather_data["main"]:
        temperature = weather_data["main"]["temp"]
        description = weather_data["weather"][0]["description"]
        print(f"{city}的天气情况:")
        print(f"温度:{temperature}°C")
        print(f"天气描述:{description}")
    else:
        print(f"无法获取{city}的天气信息。")

if __name__ == "__main__":
    api_key = "YOUR_API_KEY"  # 替换为你的OpenWeatherMap API密钥
    city = input("请输入城市名:")

    weather_data = get_weather_data(api_key, city)
    if weather_data:
        display_weather_data(weather_data, city)

在上述代码中,我们定义了两个函数:get_weather_data用于通过API获取天气数据,display_weather_data用于显示天气信息。

你需要将api_key变量替换为你的OpenWeatherMap API密钥。然后,用户可以输入城市名,并通过API获取该城市的天气数据。最后,程序将显示该城市的温度和天气描述。

运行程序后,你就可以通过输入城市名来获取该城市的天气预报。希望这个天气预报应用对你有帮助!

举报

相关推荐

0 条评论