Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - While false loop

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?

like image 527
Phoenix Avatar asked Mar 13 '14 11:03

Phoenix


People also ask

Can you do while false Python?

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.

How do you fake a while 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.

What happens if a while loop is false?

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.

What happens if the condition in a while loop is false in Python?

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.


2 Answers

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

like image 102
Silas Ray Avatar answered Sep 28 '22 11:09

Silas Ray


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.

like image 26
aragaer Avatar answered Sep 28 '22 10:09

aragaer