簡體   English   中英

超出范圍的索引不會在 Python 中引發 IndexError

[英]index out of range doesn't raise IndexError in Python

與布爾值一起使用時,可能不會引發IndexError

例如,假設

list 1 = [1, 2, 3]

這將返回True

True or True and list1[3] > 3

但這會引發IndexError

False or True and list1[3] > 3

第一行將讀取True並且不會繼續,因為有一個or所以list[3] > 3無關緊要並且不會被評估,而是返回 True 。

第二行以False + 開頭, or要求它讀取下一個 boolean 表達式以返回 output。 它將讀取True並嘗試評估list[3] > 3表達式,這將引發 IndexError

這是因為 boolean 運算符的性質
True or True and list1[3] > 3
因為您已將其編寫為True or some logic ,因為它遇到True和尾隨or它將簡單地忽略邏輯的True因為如果邏輯以True開頭並且在兩者之間有 a or之間但如果它可能是False and因為True and False返回False ,因此它將檢查邏輯的 rest。 而你的第二個以False開頭or因此如果它后面跟着一個False可以是error

因為索引號直到 2。列表索引從 0 開始。這將起作用:

首先使您的列表名稱正確:

list1 = [1, 2, 3]

False or True and list1[2] > 3

暫無
暫無

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

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