2

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.

asked Oct 8, 2013 at 21:42

2 Answers 2

12

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.

answered Oct 8, 2013 at 21:43
Sign up to request clarification or add additional context in comments.

1 Comment

ohhh okay I thought it was evaluating the code block first this makes more sense now thanks a lot!
0

if condition is False, program wont even enter the loop

answered Oct 8, 2013 at 21:49

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.