> 最新报价 > 简易的python程序

简易的python程序

简易的python程序

以下是一个简单的Python程序,它使用`requests`库获取OpenWeatherMap API的数据,并打印出指定城市的当前天气情况。

```pythonimport requests# 设置你的 OpenWeatherMap API 密钥API_KEY = \"your_api_key_here\" # 替换为你的 API 密钥BASE_URL = \"http://api.openweathermap.org/data/2.5/weather?\"def get_weather(city): # 构建请求的完整 URL url = f\"{BASE_URL}q={city}&appid={API_KEY}&units=metric&lang=zh_cn\" # 发起请求获取数据 response = requests.get(url) # 检查请求是否成功 if response.status_code == 200: # 解析 JSON 数据 weather_data = response.json() # 打印天气信息 print(f\"城市: {weather_data[\'name\']}\") print(f\"温度: {weather_data[\'main\'][\'temp\']}°C\") print(f\"天气: {weather_data[\'weather\'][\'description\']}\") else: print(f\"获取天气信息失败,状态码: {response.status_code}\")# 测试函数get_weather(\"北京\")```

这个程序首先导入了`requests`库,然后定义了一个函数`get_weather`,该函数接受一个城市名称作为参数,构建请求URL,并使用`requests.get`方法获取天气数据。如果请求成功,程序将解析返回的JSON数据,并打印出城市名称、温度和天气描述。

请确保你已经安装了`requests`库,如果没有安装,可以使用以下命令进行安装:

```shpip install requests```

此外,你需要替换`API_KEY`变量的值为你的OpenWeatherMap API密钥。你可以通过访问[OpenWeatherMap官网](https://openweathermap.org/)注册账号并获取API密钥。

其他小伙伴的相似问题:

如何获取OpenWeatherMap API密钥?

Python中如何构建天气请求URL?

如何检查请求是否成功?