我正在创建一个代码,我想在用户选择对象列表中超出范围的输入数时创建错误消息。我正在使用的代码如下:
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)
提前谢谢!
答案 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
。