如何解决 Python 中的 KeyError 问题?

DR7

我正在尝试创建一个预测工具,用于分析给定机场的历史客运量。anylysis 将基于与机场相关国家的各种 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。我想让程序说:哦不!您输入的国家不在我们的数据库中!请选择下面列出的国家之一,然后再试一次,然后打印可能的_选择变量,以便用户可以看到他有哪个选择。

非常感谢你!

罗伯特·卡恩斯

根本不需要得到一个关键错误。只需使用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')

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章