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?

Dr. Debasish Jana
  • 6,980
  • 4
  • 30
  • 69

1 Answers1

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.

arshajii
  • 127,459
  • 24
  • 238
  • 287
  • 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. – skrrgwasme Jul 22 '14 at 17:44
  • But even without the "else" ":" of while, it behaves the same, right? – Dr. Debasish Jana Jul 22 '14 at 18:03