impactblu impactblu - 5 days ago 6
Python Question

Python Indefinite loops

I can't fully understand why this:

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."


works but this doesn't:

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."


The second one doesn't even execute. My main issue is understanding how the computer is reading this and the values it is checking. I'm sorry if this seems very basic. I've been teaching myself Python and this issue arose and I could not find a sufficient explanation.

Thanks in advance.

Answer

That's because that's how a while-loop works. While-loops continue while their condition is True (or at least evaluates to True). If it is False (or evaluates to False), they break. Furthermore, the condition is reevaluated with each iteration.

With that in mind, starting with a False condition only naturally means it will never execute.

Also, this behavior is not unique to Python. All while-loops work that way. They can be understood as "while this condition is true, execute this code block".

Perhaps you were thinking of a do-while-loop, which runs a code block then evaluates the condition. However, Python doesn't have a do-while-loop.

Comments