[英]index out of range doesn't raise IndexError in Python
When used together with Booleans, the IndexError may not be raised.与布尔值一起使用时,可能不会引发IndexError 。
For example, assume例如,假设
list 1 = [1, 2, 3]
This will return True .这将返回True 。
True or True and list1[3] > 3
But this will raise IndexError .但这会引发IndexError 。
False or True and list1[3] > 3
The first line will read the True
and not continue because there is an or
so the list[3] > 3
doesn't matter and won't be evaluated, instead True is returned.第一行将读取
True
并且不会继续,因为有一个or
所以list[3] > 3
无关紧要并且不会被评估,而是返回 True 。
The second line starts with a False
+ or
requiring it to read the next boolean expressions to return the output.第二行以
False
+ 开头, or
要求它读取下一个 boolean 表达式以返回 output。 It will read True
and try to evaluate the list[3] > 3
expression which will raise the IndexError它将读取
True
并尝试评估list[3] > 3
表达式,这将引发 IndexError
This is because the nature of boolean operator这是因为 boolean 运算符的性质
True or True and list1[3] > 3
since you have written this as True or some logic
, as it encountered True
and a trailing or
it will simply ignore rest of the logic because a logic will always be True
if it starts with True
and there is a or
in between but in case of and
it could be False
since True and False
return False
thus it will check for the rest of the logic.因为您已将其编写为
True or some logic
,因为它遇到True
和尾随or
它将简单地忽略逻辑的True
因为如果逻辑以True
开头并且在两者之间有 a or
之间但如果它可能是False
and
因为True and False
返回False
,因此它将检查逻辑的 rest。 And your second one starts with False
so False
can be True if it is being followed by an or
thus it checks for your rest of the logic where it encounters an error
而你的第二个以
False
开头or
因此如果它后面跟着一个False
可以是error
Because index number is till 2. List indexes begin with 0. This will work:因为索引号直到 2。列表索引从 0 开始。这将起作用:
Make your list name right first:首先使您的列表名称正确:
list1 = [1, 2, 3]
False or True and list1[2] > 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.