Home > Blockchain >  While loop stops after else iteration
While loop stops after else iteration

Time:04-24

I am new to python and i am learning while-loops now please be nice.

So,I was playing around and i coded this program(below),in else block x is set to two so i expected a result which will iterate.But i ended up with(result 1) instead of expected(result 2) Why my loop stops after going to else block?

(code)

x = 1
while x!= 1 :
    print(x)
else:
    print(x)
    x = x 1

(result 1)

1

Process finished with exit code 0

(result 2 expected)

1
2

Process finished with exit code 0

CodePudding user response:

See here about the while-else flow: https://www.pythontutorial.net/python-basics/python-while-else/

Since x!=1 already in the first iteration, the program goes to the else statement, prints x (1), and no additional iteration is done.

CodePudding user response:

I think your while has failed and else part is triggered, the case over is value of x was 1 when you printed in else and after wards it is incremented by 1. So at the end value of x will 2.

CodePudding user response:

From the docs:

The while statement is used for repeated execution as long as an expression is true:

This repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the else clause, if present, is executed and the loop terminates.

A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and goes back to testing the expression.

Basically: The else clause of a while loop gets executed when the condition tested is False. This might also happen the first time the condition is checked, like in your case.

  • Related