Skip to content Skip to sidebar Skip to footer

Why Is This Python While Loop Not Ending?

I am wondering why this code seems to loop infinitely? The logic, while not False = while True, and this True is referring to 100 < 0 which is false, hence it should execute the

Solution 1:

a while statement should be proceeded with a conditional. The conditional True (or in your cause not False) always evaluates to True so the loop never ends.

the if block is never executed because because num < 0 never evaluates to True. Did you mean to decrement num by 1 in each iteration of the while block? If so, add a num = num - 1 within the while block:

num = 100whilenotFalse:
    if num < 0:
        break
    num = num - 1print('num is: ' + str(num))

Solution 2:

Your print statement is outside the while loop. You have to use an else clause with the if.

num = 100whilenotFalse:
    if num < 0:
        breakelse:
        print('num is: ' + str(num))
        # Do something with num to decrease it, else it will stay a forever loop.

Solution 3:

Short answer: Since the following is not true, the contents of your if clause will not be evaluated, hence the break is not performed.

ifnum<0:

All that is really running is the following:

num = 100while not False:
    if num < 0: #False#what is here is unimportant, since it will never run anyway.

...or to simplify it "all the way", this is what you're doing:

whiletrue:
    iffalse:
        break

Post a Comment for "Why Is This Python While Loop Not Ending?"