Python编写的简单天气预报应用程序示例
发布时间:2023-12-04 10:29:12
下面是一个使用Python编写的简单天气预报应用程序示例:
import requests
def get_weather(city):
# 使用API接口获取天气数据
url = f"http://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q={city}"
response = requests.get(url)
data = response.json()
# 解析天气数据
temperature = data['current']['temp_c']
condition = data['current']['condition']['text']
# 返回天气信息
return f"The current weather in {city} is {condition} with a temperature of {temperature}°C."
# 用户输入城市名称
city = input("请输入要查询的城市名称:")
# 调用函数获取天气信息
weather = get_weather(city)
# 打印天气信息
print(weather)
这个程序使用了一个天气预报的API接口,你需要在url中替换YOUR_API_KEY为你自己的API密钥。你可以在天气服务提供商的网站上注册账号并获取API密钥。
用户需要在程序中输入要查询的城市名称,然后调用get_weather函数来获取该城市的天气信息。函数内部使用requests库发送GET请求获取天气数据,并使用json库将返回的JSON数据解析为Python字典。
最后,程序打印出城市的天气信息。
以下是一个使用例子:
请输入要查询的城市名称:北京 The current weather in 北京 is Overcast with a temperature of 23°C.
这个例子演示了用户查询北京市的天气情况,天气预报显示北京的天气情况是“阴天”,当前温度为23摄氏度。
