Python不定循环
我不能完全理解为什么会这样:Python不定循环,python,loops,while-loop,Python,Loops,While Loop,我不能完全理解为什么会这样: while True: age = int(raw_input("What is your age? ")) if age >= 21: print "Okay! You are old enough to drink." break else: print "Bzzt! You are not old enough to drink." 工作正常,但这不起作用: while
while True:
age = int(raw_input("What is your age? "))
if age >= 21:
print "Okay! You are old enough to drink."
break
else:
print "Bzzt! You are not old enough to drink."
工作正常,但这不起作用:
while False:
age = int(raw_input("What is your age? "))
if age >= 21:
print "Okay! You are old enough to drink."
break
else:
print "Bzzt! You are not old enough to drink."
第二个甚至不执行。我的主要问题是理解计算机是如何读取这些数据的,以及它正在检查的值。如果这看起来很基本,我很抱歉。我一直在自学Python,但出现了这个问题,我找不到充分的解释
提前谢谢。那是因为a就是这样工作的。While循环在其条件为
True
(或至少计算结果为True
)时继续。如果为False
(或计算结果为False
),则会中断。此外,每次迭代都会重新评估该条件
记住这一点,从False
条件开始,自然意味着它永远不会执行
而且,这种行为不是Python独有的。所有的循环都是这样工作的。它们可以理解为“当此条件为真时,执行此代码块”
也许您考虑的是do while循环,它运行一个代码块,然后计算条件。但是,Python没有do while循环。如果条件为False,程序甚至不会进入循环ohhh好的,我以为它是在首先计算代码块,这现在更有意义了,非常感谢!