0

Given the following Python program,

#Version 1
x = 15
y = 8
while x - y > 0:
    x -= 2
    y += 1
    print x, y
    if x % y == 0: break
else:
        print x, y

The output comes as:

13 9
11 10
9 11
9 11

First three lines get printed within while loop and last line (9 11) gets printed again as part of the else clause. Now, another variant:

#version 2
x = 15
y = 8
while x - y > 0:
    x -= 2
    y += 1
    print x, y
    if x % y == 0: break
    else:
        print x, y

And, now the output is:

13 9
13 9
11 10
11 10
9 11
9 11

See, each x, y pair is printed twice, one by the print statement above if and one because of the else clause. Does this mean first version allow else: to go outside while loop? Isn't that strange? What could be the reason behind?

1
  • This question shows / asks the difference of else: of while and else: of if clause Commented Jul 22, 2014 at 17:55

1 Answer 1

2

while loops can have elses in Python. From while statements:

while_stmt ::=  "while" expression ":" suite
                ["else" ":" suite]

This [the while statement] 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.

Sign up to request clarification or add additional context in comments.

2 Comments

To clarify @arshajii's answer: The key difference is that in your first case, the else clause is attached to the while loop, while it is attached to the if statement in your second case.
But even without the "else" ":" of while, it behaves the same, right?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.