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?

4 Answers 4

20

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

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.

Comments

2

In python conditional statements :

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

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.

Comments

Your Answer

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.