簡體   English   中英

If Else 語句不返回 Else 語句

[英]If Else Statement Doesn't Return the Else Statement

    reject_numberList = ['1', '2', '3', '4', '5', '6']
resend_numberList = ['2', '3', '4', '5', '6', '7']

for i in range(6):
    try:
        print("Is",reject_numberList[i], "resend?")
        if(reject_numberList[i] < resend_numberList[i] and resend_numberList[i] == reject_numberList[i+1]):
            print(True)
        else:
            print(False)
    except IndexError:
        pass

這是我的代碼。 有一些數字被拒絕和反感。 但是數字 6 不會返回“False”。 這是 output:

Is 1 resend?
True
Is 2 resend?
True
Is 3 resend?
True
Is 4 resend?
True
Is 5 resend?
True
Is 6 resend?

Process finished with exit code 0

6號有什么問題?

reject_numberList[i+1]

在最后一步超出范圍並引發您捕獲並passIndexError ,因此不會引發異常並且程序結束。

由於您在 reject_numberList 上向前看,因此您會遇到異常 - 索引超出范圍 6 - 在它之后的數組中沒有項目。 如果 ti < reject_numberList.size - 1,首先檢查,如果不是,則返回 false 而不檢查該項目。

您正在迭代創建的 arrays,它具有相同數量的元素。

問題的原因是if部分:

if(reject_numberList[i] < resend_numberList[i] and resend_numberList[i] == reject_numberList[i+1]):

你的reject_numberList[i+1]將 go 越界。

tldr:你的i在最后一次迭代中的值為 6 並且reject_numberList[i+1]想要獲得reject_numberList的第 7 個元素,它不存在

您使用此代碼導致索引錯誤: reject_numberList[i+1]

這個問題源於 i 以 5 結尾的事實。因此,6 將是reject_numberList的索引。

由於列表從索引 0 開始,列表['1','2','3','4','5','6']將不接受索引 6; 6 超出了列表的范圍。

想象一下:

['1','2','3','4','5','6']
# 0   1   2   3   4   5  <- There is no sixth position, since we started at 0.

你有一個索引超出范圍的錯誤,因為 python 從 0 開始計數......數組中有 6 個元素(不確定為什么你的數字存儲為字符)但是 python 有元素 0、1、2、3, 4、5、6。為避免出現問題,請嘗試

for i in range(len(rejectNumber_list))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM