Python - For Loop

Card Puncher Data Processing

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]





Discover More
Card Puncher Data Processing
Language - Loop (For, While) - (Break, Continue)

Repeating a set of actions until a certain condition (predicate) fails is the job of programming loops; loops can take different forms, but they all satisfy this basic behavior. A loop includes: ...
Card Puncher Data Processing
Python - (Loop|Iteration)

Python - (Loop|Iteration) * * * See: Iterator Types * ...
Card Puncher Data Processing
Python - Control flow (Comparator, Boolean Operator and Conditional Statement)

in Python Equal to (==) Not equal to (!=) Less than (<) Less than or equal to (<=) Greater than (>) Greater than or equal to (>=) In (for a string or a list) Comparisons generate...



Share this page:
Follow us:
Task Runner