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?
A while statement's condition is always true or false, like the if statement. This means Boolean math can be used to control the looping. Since while False: will never execute, what will while True: do? It will infinitely loop.
while loops use only Boolean expression and when it is true. So when it gets true it'll execute until it gets false. while(false) means the condition is false which will end the loop. while(True) means the condition is True which will continue the loop.
With pretest loops such as the while loop, the program may never execute the loop statements. If the initial evaluation of the while statement's true/false expression is false, the program skips all statements of the loop and continues execution after the while statement.
When the condition becomes false, program control passes to the line immediately following the loop. In Python, all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code.
If you want 'while false' functionality, you need not
. Try while not fn:
instead.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With