如何解决 Python 中的 KeyError?

How can I work around a KeyError in Python?

我正在尝试创建一个预测工具,用于分析给定机场的历史客运量。分析将基于与机场相关国家/地区的各种 GDP(国内生产总值)的线性回归。

一个人可以输入自变量的名称,然后从 Excel 文件中得到 selected。

一旦有人回答了问题 "Which Country's GDP would you like to set as the independant variable for the Regression Analysis?",就有可能输入错误的国家/地区。在那种情况下,我会收到一个 KeyError。

我正在尝试使用 "try / except" 来解决这个问题,但我仍然收到 KeyError(请参阅第 36-49 行)。非常感谢您的帮助!

谢谢!

如果有帮助,这里是GitHubLink:https://github.com/DR7777/snowflake (参见 main_file.py 的第 36-49 行)

这是我的代码:

我尝试过 while 循环,for / except,但我似乎太新了,无法理解。


# This part saves the first row of the Excel as a list,
# so I can give the user a list of all the countries, 
# if the person types in a country, that's not on the list.

loc = ("IMF_Country_GDP_Data.xlsx") 
wb = xlrd.open_workbook(loc) 
sheet = wb.sheet_by_index(0) 
sheet.cell_value(0, 0) 
list_of_countries = sheet.row_values(0)

possible_selection = (list_of_countries[1:]) #This is the list with all the possible countries, without the Excel cell A1


#Introduction

print("Hello, welcome to the Air Traffic Forecasting Tool V0.1!")
print("Which Country's GDP would you like to set as the independant variable for the Regression Analysis?")
Country_GDP = input("Please type your answer here: ")



#here we check, if the typed Country is in the list


try:
    possible_selection == Country_GDP
    print("Your country is on the list.")

except KeyError:
    print("Oh no! You typed a country, which is not in our database!")
    print("Please select one of the countries listed below and try again")
    print(possible_selection)


#now continuing with the previous code


print("Ok, I will conduct the analysis based on the GDP of " + str(Country_GDP) + "!")
print("Here are your results: ")


#here is the rest of the code



我想实现的是: 如果一个人键入国家/地区列表中的名称,程序将运行回归。

如果国家不在列表中,我不想收到 KeyError。我希望程序说: 不好了!您输入的国家不在我们的数据库中! 请 select 下面列出的国家之一,然后重试 然后打印 possible_selection 变量,这样用户就可以看到他有哪个 selection。

非常感谢!

根本不需要得到一个关键错误。只需使用 in.

while True:
    selection = input('Which country?')
    if selection in list_of_countries: 
        print('Your country is on the list')
        break
    else:
        print('You typed an invalid entry, lets try again')