对于下面的练习,我期望为某些测试输入提供一个IndexError,但它没有发生。
目标:编写一个接受整数列表的函数,如果它包含按顺序排列的007,则返回True
My函数:
def spy_game(nums):
for x in range(len(nums)):
print(x)
try:
if nums[x]==0 and nums[x+1]==0 and nums[x+2]==7:
return(True)
except IndexError:
return(False)测试用例:
#Case 1
spy_game([1,2,4,0,0,7,5])
#Case 2
spy_game([1,0,2,4,0,5,7])
#Case 3
spy_game([1,7,2,0,4,5,0])问题:i在函数中包含了打印语句,以尝试理解问题。案例1打印0 1 2 3并返回预期的True。案例2打印0 1 2 3 4 5 6,不返回任何内容。案例3打印0 1 2 3 4 5 6并返回False。对于第2种情况和第3种情况,我都希望它能打印到5,并在那时生成一个IndexError。我不知道为什么案例2达到6,没有IndexError,为什么案例3达到6,并且确实有一个。提前感谢!
发布于 2022-01-17 01:57:55
它没有给您一个IndexError的原因是and操作是如何在代码中发生的。案例2不会到寻找x+2的地步,因为它以前在其他操作上失败了。
a = [True, True, True]
if a[0] == False and a[100000] == None:例如,永远不会给您一个IndexError,因为它在第一个if上失败。
https://stackoverflow.com/questions/70735728
复制相似问题