Python-while循环有三个条件
我正在尝试使用多个条件进行while循环:Python-while循环有三个条件,python,python-2.7,while-loop,Python,Python 2.7,While Loop,我正在尝试使用多个条件进行while循环: condition = -1 condition1 = 3 x = 2 condition2 = 5 y = 4 while not condition == 1 and not condition1 > x and not condition2 > y: print "hey" condition = 1 condition1 = 3 x = 2 while not condition == 1 and not con
condition = -1
condition1 = 3
x = 2
condition2 = 5
y = 4
while not condition == 1 and not condition1 > x and not condition2 > y:
print "hey"
condition = 1
condition1 = 3
x = 2
while not condition == 1 and not condition1 > x:
print "hey"
如果我只放了两个条件,代码会打印“嘿”,但如果我放了三个条件(这是经过验证的,因为我在测试它是否为真之前打印了条件),则不会打印
我在stackoverflow上搜索其他问题,但没有任何问题解决我的问题
有什么想法吗?求你了
condition=1
并且在程序中指定not condition==1
,这将返回false
,因此while
将计算为false。这就是为什么没有产出的原因。类似地,所有其他语句的计算结果都为false,因为您在每次检查前都放置了
not
,并且整个语句在一个完整的falsecondition2
为5,y
为4
所以condition2>y
是真的
因此not condition2>y
为false
因此,not condition==1和not condition1>x和not condition2>y
为false
因此while循环不会运行
顺便说一下,代码中还有两个问题:
while循环的第一行缺少分号
如果while循环运行一次,它将永远不会停止。您可能希望使用if
来代替只执行一次块
如果稍微对代码进行重新构造,代码的可读性会大大提高。使用我们得到的非A、非B和非C
与非(A、B或C)
相同。由于A或B或C
与any([A,B,C])
相同,因此我们可以在时将您的第一个重写为
while not any([ condition == 1,
condition1 > x,
condition2 > y ]):
print("Hey")
我们可以立即看到为什么循环没有运行,因为其中一个是True
。即condition1
(3)大于x
(2)
同样地,如果考虑第二个<代码>而循环重写为
while not any([ condition == 1,
condition1 > x ]):
print("Hey")
由于条件
等于1,因此它在第一个谓词上失败。即使条件
不等于1,条件1
(3)也大于x
(2)。所以第二个谓词也失败了。一个建议。。。相反,not condition1>x
,当条件检查布尔运算符precence的顺序时,您可以更清晰、更清晰地重写,因为您当前编写了上面的代码,while循环都不会执行<代码>而非-1==1且非3>2且非5>4
和而非1==1且非3>2
。很明显,为什么while循环都不执行(3确实大于2,1实际上等于1)。就在while
addprint not condition2>y
上方。它是错误的,因为条件2大于y。另外,由于while的主体并没有改变条件,所以最好将while改为if,在哪里可以看到缺少的分号?对不起,我指的是冒号。OP随后编辑了代码。