当输入超出列表范围时实现错误消息 - python

时间:2017-08-17 12:46:15

标签: python python-3.x error-handling indexoutofrangeexception

我正在创建一个代码,我想在用户选择对象列表中超出范围的输入数时创建错误消息。我正在使用的代码如下:

choose = int(input('Which one would you like to do a fundamental analysis on?:'))
share = (object_list[choose - 1])
print('\n-----Fundamental analysis for ' + share.company_name + '-----')
print('The company solidity is:')
print(share.solidity)
print('The company p/e value is:')
print(share.p_e)
print('The company p/s value is:')
print(share.p_s)

提前谢谢!

2 个答案:

答案 0 :(得分:2)

您可以使用try/except语句保护数组访问:

choose = int(input('Which one would you like to do a fundamental analysis on?:'))
try:
    share = (object_list[choose - 1])

except IndexError:
    # do something

但是这不会保护您免受负面索引的影响(如果choose设置为0,那么您将访问在python中有效的索引-1。所以我建议手动检查相反(我建议首先预先递减choose以符合0启动数组):

choose -= 1
if 0 < choose < len(object_list):
   # okay
   ...
else:
    raise IndexError("index out of range: {}".format(choose+1))

答案 1 :(得分:1)

添加if声明

if len(object_lis) < choose <= 0:
    print("Entered value is out of range")  

或者您可以使用try...except