【问题标题】:Python - while loop three conditions [closed]Python - while循环三个条件[关闭]
【发布时间】: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 > 4while 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


【解决方案1】:

如果您稍微重构一下代码,您的代码可能会更易读。使用DeMorgan's laws 我们得到not A and not B and not Cnot (A or B or C) 相同。由于A or B or Cany([A,B,C]) 相同,我们可以将您的第一个while 重写为

while not any([ condition == 1, 
                condition1 > x, 
                condition2 > y ]):
   print("Hey")

我们可以立即看到为什么循环没有运行,因为其中之一是True。即condition1(即3)大于x(即2)。

如果我们考虑将第二个 while 循环重写为

while not any([ condition == 1,
                condition1 > x ]):
   print("Hey") 

由于condition 等于1,它在第一个谓词上失败。即使condition 不等于1,condition1(即3)也大于x(即2)。所以第二个谓词也失败了。

【讨论】:

    【解决方案2】:

    condition2 是 5,y 是 4。

    所以condition2 > y 是真的。

    所以not condition2 > y 是假的。

    所以not condition == 1 and not condition1 > x and not condition2 > y 是假的。

    所以while循环不会运行。

    顺便说一句,您的代码中还有另外两个问题:

    1. while 循环的第一行缺少分号
    2. 如果while 循环运行一次,它就永远不会停止。您可能希望使用 if 来仅执行一次该块。

    【讨论】:

    • 您在哪里看到缺少的分号?
    • 对不起,我的意思是冒号。并且 OP 之后编辑了代码。
    【解决方案3】:

    condition=1 并在程序中指定not condition==1 将返回false,因此while 将评估为假。这就是为什么没有输出的原因。
    同样,由于您在每次检查之前放置了not,所有其他人的评估结果都为假,并且整个语句是一个完整的false

    【讨论】:

      猜你喜欢
      • 2023-03-10
      • 2011-11-02
      • 1970-01-01
      • 1970-01-01
      • 2018-08-15
      • 2020-05-27
      • 1970-01-01
      • 2022-12-07
      • 2021-05-24
      相关资源
      最近更新 更多