【问题标题】:How can I work around a KeyError in Python? [closed]如何解决 Python 中的 KeyError? [关闭]
【发布时间】:2019-08-08 22:02:26
【问题描述】:

我正在尝试创建一个预测工具,用于分析给定机场的历史客流量。分析将基于与机场相关国家的各种 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 变量,这样用户就可以看到他有哪些选择。

非常感谢!

【问题讨论】:

  • 请将您的实际代码显示为minimal reproducible examplepossible_selection == Country_GDP 行没有做任何有意义的事情,当然也不会抛出关键错误。你在哪里查找? try 需要包装将引发错误的代码。你对那条线的意图是什么?
  • 抱歉!我是 stackoverflow 的新手,也是编程的新手!下次我提出问题时,我会尝试更准确!通过possible_selection == Country_GDP 行,我试图检查保存为 Country_GDP 变量的输入是否包含在 possible_selection 列表中。

标签: python python-3.x keyerror


【解决方案1】:

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

【讨论】:

  • 哦,是的!很简单!非常感谢!今天上班前简单试了一下,好像成功了!
猜你喜欢
  • 1970-01-01
  • 2016-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-08
  • 2020-12-24
相关资源
最近更新 更多