Q: How does Python for-else work?

python code for

Answer:

To make it simple, you can think of it like that;

  • If it encounters the break command in the for loop, the else part will not be called.
  • If it does not encounter the break command in the for loop, the else part will be called.
numbers = [2, 4, 6, 8, 1]

for number in numbers:
    if number % 2 == 1:
        print(number)
        break
else:
    print("No odd numbers")

In other words, if for loop iteration is not "broken" with break, the else part will be called.


    No comments found for this tutorial, be the first to leave a comment!

Answered by
Double

Last updated on
Sep 20, 2021

Share