首页 > 解决方案 > Python If/else 混淆

问题描述

所以我的游戏有问题,我在这里复制粘贴了一部分。如您所见,仅当列表位置的前 x 个元素小于 7 并且所有其余元素均大于 7 且最终元素为 0 时,此代码才会打印 Yes。但是,正如您在示例中看到的那样, 0 不是列表中的最后一个元素,但我得到了打印是的。为什么?谢谢!

position=[3,6,4,2,5,0,10,12,7,8]
where=1
a=1
for i in range(6-where):
    if position[i]<7 and position[i]!=0:
        pass
    else:
        a=0
print(a)
for i in range(6-where,-1):
    if position[i]>6 and position[-1]==0:
        pass
    else:
        a=0
print(a)
print(position[-1])
if a==1:
    print("Yeah")

标签: pythonif-statement

解决方案


您的代码中可能有两个错误:
首先是 https://stackoverflow.com/users/10788239/arkleseisure
第一个if语句中的行必须是 if position[i]<7 and position[-1]!=0:,但是您已经编写
... and position[i]!=0
了第二个 for 循环没有被执行,因为它iterator is range(6-where,-1), range 函数默认给出一个升序迭代器,所以在你的情况下迭代器是空的。对于降序列​​表,将step参数添加到range func 并使用range(6-where, -1, -1)
这里最后一个-1范围函数的步长


推荐阅读