简体   繁体   English

为什么当条件变为 False 时 while 循环不停止?

[英]Why doesn't the while loop stop when the condition becomes False?

I am a beginner in Python and was watching a 6 hr video by Mosh Hamedami.我是 Python 的初学者,正在观看 Mosh Hamedami 的 6 小时视频。 He has shown an example of designing an elementary Car Game using a while loop.他展示了一个使用 while 循环设计基本汽车游戏的示例。 The code is suggested is below:建议的代码如下:

command = ''
started = False
while command != 'quit':
    command = input('Enter a Command: ').lower()
    if command == 'start':
        if started:
            print("Car already Started! Let's go!")
        else:
            started = True
            print("Car Started.... Ready to Go!!!")
    elif command == 'stop':
        if not started:
            print('Car already stopped!')
        else:
            started = False
            print('Car stopped!')
    elif command == 'help':
        print(" 'start' - to start the car\n'stop' - to stop the car\n'quit' - to quit/close the game.")

    elif command == 'quit':
        break
    else:
        print('Sorry, I do not understand that!')

The above program runs perfectly, But if we exclude the elif command == 'quit' block of code from the above program, and give the User-input: 'quit' the program returns the Output: Sorry, I do not understand that, But according to my understanding of the while loop: when: User-input.上面的程序运行完美,但是如果我们从上面的程序中排除 elif 命令 == 'quit' 代码块,并给用户输入:'quit' 程序返回输出:对不起,我不明白,但是根据我对while循环的理解: when: User-input. 'quit' The while loop should stop getting executed since while condition becomes False. 'quit' while 循环应该停止执行,因为 while 条件变为 False。

Now, if while loop stops executing with user-input "quit" then how the else block defined within the while condition is getting executed?现在,如果 while 循环在用户输入“quit”时停止执行,那么 while 条件中定义的 else 块是如何执行的?

The program actually stops when you type quit , but before stopping it prints "Sorry, I do not understand that.".该程序实际上在您键入quit时停止,但在停止之前它会打印“抱歉,我不明白。”。 You can fix this by putting command = input('Enter a Command: ').lower() before while and in the end of the while like this (so that while will check if command != quit immediately after inputing):您可以通过像这样在while之前和结束while放置command = input('Enter a Command: ').lower()来解决此问题(这样while将检查command != quit ):

command = ''
started = False
command = input('Enter a Command: ').lower()
while command != 'quit':
    if command == 'start':
        if started:
            print("Car already Started! Let's go!")
        else:
            started = True
            print("Car Started.... Ready to Go!!!")
    elif command == 'stop':
        if not started:
            print('Car already stopped!')
        else:
            started = False
            print('Car stopped!')
    elif command == 'help':
        print(" 'start' - to start the car\n'stop' - to stop the car\n'quit' - to quit/close the game.")
    else:
        print('Sorry, I do not understand that!')
    command = input('Enter a Command: ').lower()

A while loop does not terminate when the condition becomes false.当条件变为假时, while循环不会终止。 It terminates when it evaluates the condition and the condition is found to be false.它在评估条件并发现条件为假时终止。 That evaluation doesn't happen until the beginning of each loop iteration, not immediately after some event occurs that will allow the condition to become false.该评估直到每次循环迭代开始时才会发生,而不是在某些允许条件变为假的事件发生后立即发生。

A better way to write this loop is to simply use True as the condition, as it doesn't require you to initialize command to a known non-terminating value, then let a break statement somewhere the loop terminate the command when appropriate.编写此循环的更好方法是简单地使用True作为条件,因为它不需要您将command初始化为已知的非终止值,然后让循环中某处的break语句在适当的时候终止命令。

started = False
while True:
    command = input('Enter a Command: ').lower()
    if command == 'quit':
        break

    if command == 'start':
        if started:
            print("Car already Started! Let's go!")
        else:
            started = True
            print("Car Started.... Ready to Go!!!")
    elif command == 'stop':
        if not started:
            print('Car already stopped!')
        else:
            started = False
            print('Car stopped!')
    elif command == 'help':
        print(" 'start' - to start the car\n'stop' - to stop the car\n'quit' - to quit/close the game.")
    else:
        print('Sorry, I do not understand that!')

Of course, you don't need two separate if statements as I've shown here;当然,您不需要两个单独的if语句,就像我在这里展示的那样; you could combine them into one with if command == 'start' being the first elif clause of the combined if statement.您可以将它们组合成一个if command == 'start'作为组合if语句的第一个elif子句。 But this provides an explicit boundary between "code that terminates the loop" and "code that allows the loop to continue".但这在“终止循环的代码”和“允许循环继续的代码”之间提供了明确的界限。

Statement are executed sequentially.语句是顺序执行的。
The condition of the while statement is executed at the beginning of the loop while the "else:" is executed near the end. while 语句的条件在循环开始时执行,而“else:”在接近结束时执行。 After the "input" is executed, the "else" near end of loop is executed first.执行完“input”后,先执行接近循环末尾的“else”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM