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



我是Python的初学者,正在观看Mosh Hamedami的6小时视频。他展示了一个使用while循环设计初级汽车游戏的例子。建议代码如下:

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 carn'stop' - to stop the carn'quit' - to quit/close the game.")
elif command == 'quit':
break
else:
print('Sorry, I do not understand that!')

上面的程序运行完美,但是如果我们从上面的程序中排除elif命令== 'quit'代码块,并给出用户输入:"辞职"程序返回输出:对不起,我不明白!但是根据我对while循环的理解,当:用户输入:"辞职"当while条件变为False时,while循环应该停止执行。

现在,if while循环停止执行,用户输入&;quit&;那么在while条件中定义的else块是如何执行的呢?

当条件变为false时,while循环不会终止。当它计算条件并且发现条件为假时终止。该计算直到每次循环迭代开始时才会发生,而不是在允许条件变为false的事件发生后立即发生。

编写这个循环的更好的方法是简单地使用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 carn'stop' - to stop the carn'quit' - to quit/close the game.")
else:
print('Sorry, I do not understand that!')

当然,您不需要两个单独的if语句,就像我在这里展示的那样;您可以将它们合并为一个,其中if command == 'start'是合并后的if语句的第一个elif子句。但是这在终止循环的代码之间提供了一个明确的边界。和允许循环继续的代码。

当您输入quit时,程序实际上停止了,但在停止之前它会打印"Sorry, I do not understand that!"您可以通过将command = input('Enter a Command: ').lower()放在while之前并在while的末尾来修复此问题,这样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 carn'stop' - to stop the carn'quit' - to quit/close the game.")
else:
print('Sorry, I do not understand that!')
command = input('Enter a Command: ').lower()

语句依次执行。
while语句的条件在循环开始时执行,而"else:"在接近结束时执行。在"输入"之后,则执行"else"首先执行循环的近末端。

最新更新