Python 天气API响应中的关键错误

Python 天气API响应中的关键错误,python,keyerror,weather,Python,Keyerror,Weather,我正在制作一个python程序,它讲述天气,但遇到以下错误 请告诉我如何改正它 代码 import requests import json api = "<MY_API_KEY>" BASE_URL = "https://api.openweathermap.org/data/2.5/weather?" print("for which city?") CITY = input("city?: ")

我正在制作一个python程序,它讲述天气,但遇到以下错误

请告诉我如何改正它

代码

import requests
import json

api = "<MY_API_KEY>"
BASE_URL = "https://api.openweathermap.org/data/2.5/weather?"
print("for which city?")
CITY = input("city?: ")
URL = BASE_URL + "q=" + CITY + "&appid=" + api

response = requests.get(URL)
if __name__ == "__main__":
    data = response.json()
    main = data['main']
    temperature = main['temp']
    humidity = main['humidity']
    pressure = main['pressure']
    report = data['weather']
    print(f"{CITY:-^30}")
    print(f"Temperature: {temperature}")
    print(f"Humidity: {humidity}")
    print(f"Pressure: {pressure}")
    print(f"Weather Report: {report[0]['description']}")

导入请求
导入json
api=“”
基本URL=”https://api.openweathermap.org/data/2.5/weather?"
打印(“哪个城市?”)
城市=输入(“城市:”)
URL=BASE\u URL+“q=“+CITY+”&appid=“+api
response=requests.get(URL)
如果名称=“\uuuuu main\uuuuuuuu”:
data=response.json()
main=数据['main']
温度=主['temp']
湿度=主[“湿度”]
压力=主[‘压力’]
报告=数据[“天气”]
印刷品(f“{CITY:-^30}”)
打印(f“温度:{Temperature}”)
打印(f“湿度:{湿度}”)
打印(f“压力:{Pressure}”)
打印(f“天气报告:{Report[0]['description']}”)
终端

PS C:\Users\mamta\Documents\PythonPanti\JARVISprj>  c:; cd 'c:\Users\mamta\Documents\PythonPanti\JARVISprj'; & 'C:\Users\mamta\AppData\Local\Programs\Python\Python39\python.exe' 'c:\Users\mamta\.vscode\extensions\ms-python.python-2021.5.842923320\pythonFiles\lib\python\debugpy\launcher' 
'53873' '--' 'c:\Users\mamta\Documents\PythonPanti\JARVISprj\exp.py'
for which city?
city?: Delhi
Traceback (most recent call last):
  File "c:\Users\mamta\Documents\PythonPanti\JARVISprj\exp.py", line 13, in <module>
    main = data['main']
KeyError: 'main'
PS C:\Users\mamta\Documents\PythonPanti\JARVISprj>C:;cd'c:\Users\mamta\Documents\PythonPanti\JARVISprj';&'C:\Users\mamta\AppData\Local\Programs\Python\Python39\Python.exe''C:\Users\mamta\.vscode\extensions\ms Python.Python-2021.5.842923320\pythonFiles\lib\Python\debugpy\launcher'
“53873”-“c:\Users\mamta\Documents\PythonPanti\JARVISprj\exp.py”
去哪个城市?
城市?:德里
回溯(最近一次呼叫最后一次):
文件“c:\Users\mamta\Documents\PythonPanti\JARVISprj\exp.py”,第13行,在
main=数据['main']
KeyError:'main'

您的代码非常好,我看到的唯一问题是当您输入任何垃圾值时。您需要进行错误处理。

检查您的API密钥,它似乎无效。另外,永远不要与任何人共享API密钥,尤其是在这样的公共论坛上。我不确定共享API密钥是否明智。关于KeyError-它只是告诉您响应对象中没有“main”键。我建议打印“数据”。@chmielcode我运行了查询,这是一个API键错误。检查您的代码的响应。这里我看到的唯一问题是当您输入任何垃圾值时。好的,谢谢,谢谢(你为什么要说两遍)