samedi 17 mars 2018

For loop with if and else condition [duplicate]

This question already has an answer here:

I am kind of confuse by the use of else in iteration sometimes, need some explanation if you can:

# Example 1:
for i in [1,2,3,2,1]:
    if i < 3:
        print(i)
else:
    print('OK!')
# >>>
# 1
# 2
# 2
# 1
# OK!

# Example 1b:
for i in [1,2,3,2,1]:
    if i < 3:
        print(i)
        break
else:
    print('OK!')
# >>>
# 1

Here in example 1, I have an else after the for loop. after the iteration is over for the for loop, OK is printed.

But in example 1b, with a break after if, once it breaks the for loop, that else condition will not print.

What does else do here in both examples at all? Because if I remove the else:

# Example 2:
for i in [1,2,3,2,1]:
    if i < 3:
        print(i)
print('OK!')
# >>>
# 1
# 2
# 2
# 1
# OK!

# Example 2b:
for i in [1,2,3,2,1]:
    if i < 3:
        print(i)
        break
print('OK!')
# >>>
# 1
# OK!

Obviously, OK will be printed in both Example 2 and 2b.

Thanks!

Aucun commentaire:

Enregistrer un commentaire