Search code examples
pythonloopsfor-loopindentation

Is else outside for loop, if yes why else is not executing?


numbers = [10, 20, 33, 55, 39, 55, 75, 37, 21, 23, 41, 13]

for num in numbers:
    if num % 2 == 0:
       print(num)
       break
else:
   print(num)

In the above code i do have else block corresponding to for loop and which is not getting executed. can someone guide me why it is not executing ?


Solution

  • Yes the else block is corresponded to for loop, but it will execute only if break is NEVER executed. Since you have the even numbers in numbers list break is executed and which is why else is not executed

    for num in numbers:
      if num % 2 == 0:
         print(num)
         break
    else:
      print(num)
    

    Try with this list number=[11,22,33], else block will get executed, for more information 4.4. break and continue Statements, and else Clauses on Loops

    Python has different syntax where Loop statements may have an else clause

    Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the iterable (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement. This is exemplified by the following loop, which searches for prime numbers: