【发布时间】:2016-03-15 06:02:55
【问题描述】:
我正在尝试使用多个条件创建一个 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 condition1 > x:
print "hey"
如果我只输入两个条件,代码会打印“嘿”,但如果我输入三个条件(即已验证,因为我之前打印条件以测试它是否为真),则不会打印。
我在 stackoverflow 上搜索其他问题,但没有解决我的问题。
有什么想法吗?请。
【问题讨论】:
-
一个建议...而不是
not condition1 > x,您可以将condition <= x重写为更清晰、更易读 -
检查布尔运算符优先级的顺序
-
由于您目前已经编写了上面的代码,因此 while 循环都不会执行。
while not -1 == 1 and not 3 > 2 and not 5 > 4和while not 1 == 1 and not 3 >2。为什么没有执行while循环应该很明显(3确实大于2,1实际上等于1)。 -
在
while上方添加print not condition2 > y。其为 False,因为 condition2 大于 y。 -
还鉴于 while 的主体不会改变条件,最好将 while 更改为 if
标签: python python-2.7 while-loop