当输入超出列表范围时执行错误消息 - python
Implementing error message when input is out of range in a list - python
我正在创建一个代码,当用户选择一个超出对象列表范围的输入数字时,我想在其中创建一条错误消息。我正在使用的代码如下:
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)
提前致谢!
您可以使用 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-start 数组):
choose -= 1
if 0 < choose < len(object_list):
# okay
...
else:
raise IndexError("index out of range: {}".format(choose+1))
添加 if
语句
if len(object_lis) < choose <= 0:
print("Entered value is out of range")
或者您可以使用 try...except
.
我正在创建一个代码,当用户选择一个超出对象列表范围的输入数字时,我想在其中创建一条错误消息。我正在使用的代码如下:
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)
提前致谢!
您可以使用 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-start 数组):
choose -= 1
if 0 < choose < len(object_list):
# okay
...
else:
raise IndexError("index out of range: {}".format(choose+1))
添加 if
语句
if len(object_lis) < choose <= 0:
print("Entered value is out of range")
或者您可以使用 try...except
.