10
fn='a'
x=1
while fn:
 print(x)
 x+=1
 if x==100:
 fn=''

Output: 1 ... 99

fn=''
x=1
while fn:
 print(x)
 x+=1
 if x==100:
 fn='a'

Output: while loop does not run.


What is the reason for the while loop not running?

Is it that the condition that ends a while loop is 'False' and therefore it's not capable of performing 'while false' iterations?

asked Mar 13, 2014 at 11:48

4 Answers 4

20

If you want 'while false' functionality, you need not. Try while not fn: instead.

answered Mar 13, 2014 at 11:54
Sign up to request clarification or add additional context in comments.

Comments

5

The condition is the loop is actually a "pre-" condition (as opposed to post-condition "do-while" loop in, say, C). It tests the condition for each iteration including the first one.

On first iteration the condition is false, thus the loop is ended immediately.

answered Mar 13, 2014 at 11:50

Comments

2

In python conditional statements :

'' is same as False is same as 0 is same as []

answered Mar 13, 2014 at 11:50

Comments

0

Consider your loop condition to be translated into this:

fn=''
x=1
while len(fn)>0:
 print(x)
 x+=1
 if x==100:
 fn='a'

while checks if the string is not empty at the beginning of each iteration.

answered Mar 13, 2014 at 11:50

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.