如何解决 Python 中的 KeyError?

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


一个人可以输入独立变量的名称,然后从 Excel 文件中选择该名称。


一旦有人收到“您希望将哪个国家的 GDP 设置为回归分析的自变量?”的问题,就有可能输入错误的国家/地区。在那种情况下,我会收到一个 KeyError。


我正在尝试使用“try / except”来解决这个问题,但我仍然收到 KeyError(参见第 36-49 行)。我真的很感激一些帮助!


谢谢!


如果有帮助,这里是 GitHub 链接: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。我想让程序说:哦不!您输入的国家/地区不在我们的数据库中!请选择下面列出的国家之一,然后再试一次,然后打印 possible_selection 变量,这样用户就可以看到他有哪个选项。


Qyouu
浏览 521回答 1
1回答

慕婉清6462132

根本不需要得到关键错误。只需使用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')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python