-3

I already have a lot of experience in Python, but recently I've seen some people using else at the end of a while or for block. I was very curious and decided to test:

for i in range(2):
    print(i)
else:
    print("Something...")

Output:

0
1
Something...

Using or not else, the code will execute the same way, so what's the use of this?

JeanExtreme002
  • 200
  • 3
  • 14
  • 3
    You can read about that [in the documentation](https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops). – larsks Dec 20 '19 at 00:14

1 Answers1

3

else after a for or while block will execute if and only if the block terminates normally. If you leave through a break or exception, that else block gets skipped.

for i in range(2):
    print(i)
    break
else:
    print("Something...")

Output:

0
Prune
  • 76,765
  • 14
  • 60
  • 81