欢迎访问宙启技术站
智能推送

使用Python编写案例:创建一个简单的天气预报应用程序

发布时间:2023-12-04 13:54:14

以下是一个简单的天气预报应用程序的Python代码示例:

import requests
from datetime import datetime

def get_weather_data(city):
    api_key = "YOUR_API_KEY"  # 替换为你的实际API密钥
    base_url = "http://api.openweathermap.org/data/2.5/weather"
    params = {
        "q": city,
        "appid": api_key,
        "units": "metric"
    }
    response = requests.get(base_url, params=params)
    data = response.json()

    if data["cod"] == "404":
        print("无法获取该城市的天气信息。")
    else:
        weather = {
            "城市": data["name"],
            "国家": data["sys"]["country"],
            "温度": data["main"]["temp"],
            "天气": data["weather"][0]["main"],
            "描述": data["weather"][0]["description"],
            "风速": data["wind"]["speed"],
            "湿度": data["main"]["humidity"]
        }
        return weather

def print_weather(weather):
    print("城市:", weather["城市"])
    print("国家:", weather["国家"])
    print("日期和时间:", datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    print("温度:", weather["温度"], "摄氏度")
    print("天气:", weather["天气"])
    print("描述:", weather["描述"])
    print("风速:", weather["风速"], "m/s")
    print("湿度:", weather["湿度"], "%")

def main():
    city = input("请输入城市名:")
    weather = get_weather_data(city)

    if weather:
        print_weather(weather)

if __name__ == "__main__":
    main()

上述代码通过使用OpenWeatherMap的API来获取天气数据。你需要将YOUR_API_KEY替换为你的实际API密钥,你可以在OpenWeatherMap网站上注册以获取一个免费的API密钥。

这个程序首先通过用户输入获取要查询的城市名称,然后调用get_weather_data函数来获取该城市的天气数据。然后,它将天气数据打印出来,包括城市名称、国家、温度、天气情况、描述、风速和湿度。

你可以根据自己的需要自定义输出格式或添加其他功能。