请为我写一个简单的python查询天气的小程序
当然可以!下面是一个简单的Python查询天气的小程序:
import requests
def get_weather(city):
url = f"http://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q={city}"
response = requests.get(url)
data = response.json()
if 'error' in data:
print("查询天气失败,请检查城市名称是否正确。")
else:
location = data['location']['name']
temp_c = data['current']['temp_c']
condition = data['current']['condition']['text']
print(f"{location}的天气情况:")
print(f"温度:{temp_c}°C")
print(f"天气状况:{condition}")
city = input("请输入要查询的城市名称:")
get_weather(city)
在上述代码中,你需要将YOUR_API_KEY替换为你自己的WeatherAPI API密钥。你可以在WeatherAPI官网注册账号并获取API密钥。
运行程序后,它会要求你输入一个城市名称。然后,它将使用WeatherAPI获取该城市的天气信息,并将其打印出来。如果城市名称无效或查询失败,它将打印出错误信息。
请确保在运行程序之前安装requests库,你可以使用以下命令安装它:
pip install requests
希望对你有帮助
原文地址: https://www.cveoy.top/t/topic/iSrA 著作权归作者所有。请勿转载和采集!