【问题标题】:Why does the while loop never stop looping?为什么while循环永远不会停止循环?
【发布时间】:2022-01-22 12:09:43
【问题描述】:

下面是我的代码的 sn-p。假设 while 循环内play_again() 的输出返回 False。那么,为什么我的while循环一直在循环呢?有什么我不知道的概念吗?

game_list = ['0','1','2']

while True:

    position = myfunc()
    
    replacement(game_list,position)
    
    play_again()

print(game_list)

【问题讨论】:

  • while true 永远不会停止,除非你告诉它中断。
  • "while 循环返回 False" 但您不会将返回值存储在任何地方或更新 while 循环条件。您的 while 循环永久卡在 while True
  • 是的,但我不希望它破坏,直到我告诉它,所以再次使用 play_!
  • play_again 返回什么无关紧要,因为它永远不会被评估。 while True 确实会无限循环。
  • "但我不希望它崩溃,直到我告诉它 如果play_again 的输出为 False,那你为什么不想 @987654327 @?

标签: python while-loop


【解决方案1】:

这是 b/c,while True 不会结束,除非您使用关键字 break,它会在循环外中断并继续代码。 while True 永无止境

while 循环

while (condition):
    #code

在条件为False 之前永远不会结束,对于True 条件,女巫永远不会为真。

你的代码应该是:

game_list = ['0','1','2']

while True:

    position = myfunc()

    replacement(game_list,position)

    if not play_again():
         break
print(game_list)

或者你可以这样做:

game_list = ['0','1','2']

while play_again():

    position = myfunc()

    replacement(game_list,position)

print(game_list)

【讨论】:

  • James- 您好,感谢您的回答。您的答案第一行-这是 b/c while True....... 但是如果我们返回 False 呢?它还应该导致 while 循环中断
  • 不,b/c 如果条件为真,while 循环将继续,真总是为真,所以它不会,如果你返回一些东西,它不会进入条件。
  • 我建议 OP 使用您的第二个 sn-p 代码,而不是第一个。无论如何很好的解释,+1
【解决方案2】:

这段代码应该可以工作:

while (play_again()):
    position = myfunc()
    replacement(game_list,position)

您应该知道,在 Python 中,while 循环(与其他所有编程语言一样)采用单个“参数”,即 condition 类型的 bool

while (i > 3): # i>3 is a boolean condition
    ...

其实这等价于

while (True): # the loop continues until condition is False, so in this case it will never stop
    if (i > 3):
        break

在 Python 中,break 是一个让你退出循环的关键字。


那么,你可能明白,这段代码相当于这个答案中的第一个sn-p:

while (True):
    position = myfunc()
    replacement(game_list,position)
    if (not play_again()):
        break

【讨论】:

  • 是的,但是在while True 中返回False 也应该结束while loop
  • 没有。如果您在没有赋值的情况下返回,则该值(在本例中为 False)只是丢失了。想象一下,如果您在 while 循环中调用一个返回 True 的函数和一个返回 False 的函数。编译器如何知道它是否必须继续或中断循环?
  • 知道了。谢谢 :)
【解决方案3】:

而 True 将一直运行,直到您决定中断。

game_list = ['0','1','2']
while True:

    position = myfunc()
    
    replacement(game_list,position)
    
    play_again = input("do you want to play again?")
    if play_again == 'y':

        play_again()
    else:
        break

print(game_list)

【讨论】:

    猜你喜欢
    • 2018-08-14
    • 2021-11-28
    • 1970-01-01
    • 2015-04-21
    • 2014-01-31
    • 1970-01-01
    • 2014-05-30
    • 1970-01-01
    • 2011-01-20
    相关资源
    最近更新 更多