1

我正在創建一個代碼,當用戶在對象列表中選擇超出範圍的輸入數字時,我想創建一條錯誤消息。我正在使用的代碼如下:當輸入超出列表中的範圍時執行錯誤消息 - 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) 

預先感謝您!

+0

使用'try' /'除了IndexError:' – JohanL

+0

@coldspeed:很好找。但是,原始答案不檢查負指數。嘗試/除非在該特定情況下效率低下。那麼,我會回答這樣的原始問題,但我回答了一個,而不是... –

回答

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,那麼你訪問索引-1這是有效的。蟒蛇所以我建議手動檢查來代替(我建議到預減choose先遵守,以0開始排列):

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

這看起來很有希望!我複製它,並放在我的代碼周圍,但我仍然只是從程序gett索引錯誤..我真的不明白什麼是錯的!編輯:得到它現在的工作!謝謝! – Jurkka

1

添加if聲明

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

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

+1

如果'choose'是0或負數? –

+0

@ Jean-FrançoisFabre;接得好。 – haccks

+1

嘗試/除了一般更好,但手動檢查在這種情況下是安全的,因爲負指數,是的。 –

相關問題