9
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?

Phoenix
  • 4,386
  • 10
  • 40
  • 55

4 Answers4

19

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

Silas Ray
  • 25,682
  • 5
  • 48
  • 63
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.

aragaer
  • 17,238
  • 6
  • 47
  • 49
2

In python conditional statements :

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

Arovit
  • 3,579
  • 5
  • 20
  • 24
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.