-2

Maybe that's a stupid question and a stupid mistake by me but i can't get this control flow to work. here is my simplified code:

for x in range(1,10):
    print(x)
    if x==2:
        print("working")
        break
else:
    print("stop")

here is the result on shell:

1
2
working

Anyone can help me?

nbro
  • 15,395
  • 32
  • 113
  • 196
elunaery
  • 69
  • 1
  • 7
  • What output did you expect? – Aran-Fey Jan 13 '15 at 16:19
  • 2
    This is doing exactly as it should, if you always want the stop to print remove the else and put the print outside the loop – Padraic Cunningham Jan 13 '15 at 16:20
  • Looking at this question the output you got was expected. If you want the `for loop` to print 'Stop', then it needs to have not been `break`'d. The `else` clause in `for loops` is only executed when a `for loop` has been completely run. – NDevox Jan 13 '15 at 16:20
  • i was expecting the else clause to be executed when the break was used. My Bad, i did not understand the documentation well enough. Thank you for the help. – elunaery Jan 13 '15 at 16:26

1 Answers1

3

Your program is working as expected and specified. From the official Python 3 documentation:

A break statement executed in the first suite terminates the loop without executing the else clause’s suite.

Marcus Müller
  • 34,677
  • 4
  • 53
  • 94