为什么 while 循环永远不会停止循环?

Why does the while loop never stop looping?

下面是我的代码片段。让我们假设 while 循环中 play_again() 的输出 returns False。那么,为什么我的while循环一直在循环呢?有什么我不知道的概念吗?

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

while True:

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

print(game_list)

这是 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)

此代码应该有效:

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

你应该知道在 Python 中,一个 while 循环(就像在所有其他编程语言中一样)接受一个“参数”,即 condition 类型 [=16] =]:

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是一个让你退出循环的关键字。


那么,正如您可能理解的那样,此代码相当于此答案中的第一个片段:

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

而 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)