0

Pretty simple question really but something I really don't understand. I would expect the below code to print 3 * 'x', but it only prints it twice. I know raised becomes 3 which breaks the loop, but I'm expecting the 'x' to be printed before it breaks.

So raised is < 3 twice, expecting 2 * 'x', then a third should print when the else statement runs. So why does it only print 2 * 'x'?

raised = 1
while raised < 5:
    raised +=1
    print(raised)
    print('x')
    if raised == 3:
        break
else:
    print('x')
Mrmoleje
  • 453
  • 1
  • 12
  • 35
  • 2
    The `else` statement is only executed when the condition in `while` becomes `False`. When you `break` it is still `True` https://stackoverflow.com/questions/3295938/else-clause-on-python-while-statement – Tzane Apr 07 '23 at 08:59
  • 1
    Does this answer your question? [Why does python use 'else' after for and while loops?](https://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops) – Nick Apr 07 '23 at 09:00
  • @Tzane you should vote to close as a dupe of that question... I picked the wrong one... – Nick Apr 07 '23 at 09:00

1 Answers1

-2

The output I reckon you'd get in this case is: 2 x x 3 x

first the value of 'raised' variable followed by the 'x' from before the if statement and the 'x' from the else statement. Then we go to the next iteration and get '3' as the value of raised. followed by an 'x' then we break out of the code.

Dhruva
  • 11
  • 2
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 10 '23 at 06:30