Python Tutorial

Monday, December 9, 2013

Python for loop with else clauses


Python for loop with else condition is very interesting feature. This types of feature makes code more readable and pythonic. Lets see an example.

a = [1, 3, 51, 7, 8]
print a
k = 5
for n in a:
    if n%k==0:
        print "Divisible by",k,"found"
        break
else:
    # This line will working if for loop terminate normally
    print "Divisible by",k,"not found"

print
a = [1, 3, 5, 7, 8]
print a
k = 5
for n in a:
    if n%k==0:
        print "Divisible by",k,"found"
        break
else:
    # This line will working if for loop terminate normally
    print "Divisible by",k,"not found"


Output:
[1, 3, 51, 7, 8]
Divisible by 5 not found

[1, 3, 5, 7, 8]
Divisible by 5 found

0 comments:

Post a Comment