Table of Contents

About

For Loop in Python

Statement

Reversed

for i in reversed(range(4)):
    print(i)
3
2
1
0

Break

The else statement is executed after the for, but only if the for ends normally without a break.

for n in numbers:
    if (n % 2 != 0 ):
        print n, 'is not even'
        break
else:
    print 'All numbers are even'

For the following numbers,

numbers = [2, 4, 5, 6]

the script will print:

5 is not even

For the following numbers,

numbers = [2, 4, 6]

the script will print:

All numbers are even

Continue

The continue statement, also borrowed from C, continues with the next iteration of the loop:

for num in range(2, 10):
    if num % 2 == 0:
        continue
        print "You will not see this print"
    else:
        print "Found an noneven number", num
Found an uneven number 3
Found an uneven number 5
Found an uneven number 7
Found an uneven number 9

Underscore

Sometimes, you just want to loop and not using the element of a list. For this purpose, you can use the underscore.

[1 for _ in range(3)]
[1, 1, 1]