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