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
If you want 'while false' functionality, you need not. Try while not fn: instead.
Comments
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
In python conditional statements :
'' is same as False is same as 0 is same as []
Comments
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
Explore related questions
See similar questions with these tags.