【问题标题】:Why is this python while loop not ending?为什么这个 python while 循环没有结束?
【发布时间】:2020-01-17 05:59:38
【问题描述】:

我想知道为什么这段代码似乎无限循环?逻辑,while not False = while True,这个 True 指的是 100 < 0,这是错误的,因此它应该执行 print 语句,对吗?那么为什么会卡在循环中..?

num = 100
while not False:
    if num < 0:
        break
print('num is: ' + str(num))

【问题讨论】:

  • 做一些rubber duck debugging,并弄清楚num如何变得小于零(这是你必须打破循环的唯一条件)。

标签: python while-loop


【解决方案1】:

while 语句应该带有条件。有条件的True(或在你的原因not False)总是评估为True,所以循环永远不会结束。

if 块永远不会执行,因为num &lt; 0 永远不会计算为True。您的意思是在 while 块的每次迭代中将 num 减 1 吗?如果是这样,请在 while 块中添加 num = num - 1

num = 100
while not False:
    if num < 0:
        break
    num = num - 1
print('num is: ' + str(num))

【讨论】:

    【解决方案2】:

    您的print 语句位于while 循环之外。您必须使用带有ifelse 子句。

    num = 100
    while not False:
        if num < 0:
            break
        else:
            print('num is: ' + str(num))
            # Do something with num to decrease it, else it will stay a forever loop.
    

    【讨论】:

      【解决方案3】:

      简短回答:由于以下不正确,您的if 子句的内容将不会被评估,因此break 不会被执行。

      if num < 0:
      

      真正运行的是以下内容:

      num = 100
      while not False:
          if num < 0: #False
              #what is here is unimportant, since it will never run anyway.
      

      ...或者为了简化它“一直”,这就是你正在做的事情:

      while true:
          if false:
              break
      

      【讨论】:

        猜你喜欢
        • 2017-04-18
        • 2017-04-03
        • 1970-01-01
        • 2020-09-13
        • 1970-01-01
        • 1970-01-01
        • 2014-03-24
        • 2019-06-16
        • 1970-01-01
        相关资源
        最近更新 更多