0
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 ?

Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
Anuvicleo
  • 107
  • 1
  • 7

4 Answers4

4

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:

Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
0

There is no "if" for that else. I think you need something like this:

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

for num in numbers:
    if num % 2 == 0:
        print(num)
        break
print(num)
user3503711
  • 1,623
  • 1
  • 21
  • 32
0

Indentaion seems to be wrong, try this.

for num in numbers:
    if num % 2 == 0:
        print(num)
        break
    else:
        print(num)
User
  • 101
  • 1
  • 9
0

I think its better to demonstrate this with varying tests. So a for loop can have an else block. the else block is only executed if the loop completed normally. I.E there was not break in the loop. if we create a function that takes a list and a divider. we can see that if the if condition is matched and we print then break, the else block is never run. Only if we run all the way through the loop without break then the else is executed

def is_divisable_by(nums, divider):
    for num in nums:
        if num % divider == 0:
            print(num, "is divsiable by ", divider)
            break
    else:
        print("none of the numbers", nums, "were divisable by", divider)

numbers = [1, 6, 3]
numbers2 = [7, 8, 10]
is_divisable_by(numbers, 2)
is_divisable_by(numbers, 7)
is_divisable_by(numbers2, 4)
is_divisable_by(numbers2, 6)

OUTPUT

6 is divsiable by  2
none of the numbers [1, 6, 3] were divisable by 7
8 is divsiable by  4
none of the numbers [7, 8, 10] were divisable by 6
Chris Doyle
  • 10,703
  • 2
  • 23
  • 42