用Python编写一个简单的天气预报应用
发布时间:2023-12-04 18:45:56
下面是一个使用Python编写的简单天气预报应用的示例代码:
import requests
import json
def get_weather(city):
api_key = 'your_api_key' # 需要替换为您自己的API密钥
url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}'
response = requests.get(url)
data = json.loads(response.text)
description = data['weather'][0]['description']
temperature = data['main']['temp'] - 273.15 # 转换为摄氏度
humidity = data['main']['humidity']
return description, temperature, humidity
def main():
city = input('请输入要查询天气的城市:')
description, temperature, humidity = get_weather(city)
print(f'城市:{city}')
print(f'天气:{description}')
print(f'温度:{temperature:.2f}℃')
print(f'湿度:{humidity}%')
if __name__ == '__main__':
main()
使用方法:
1. 在get_weather函数中,将api_key替换为您自己的OpenWeatherMap API密钥。需要在OpenWeatherMap网站上创建一个帐户并申请API密钥。
2. 运行以上代码,程序将提示您输入要查询天气的城市。
3. 程序将使用OpenWeatherMap API获取所选城市的天气数据,并将天气描述、温度和湿度打印到控制台。
请注意,由于使用了OpenWeatherMap的API,您需要创建一个OpenWeatherMap帐户并获取您自己的API密钥。此代码的输出结果只提供了基本的天气信息,您可以根据OpenWeatherMap API的文档来获取更多详细的天气数据。
