Repeating statements with loops

Loops are used to repetitively execute a sequence of statements while changing a variable from iteration to iteration. This variable is called the index variable. It is successively assigned to the elements of a list, (refer to Chapter 9, Iterating) :

L = [1, 2, 10]
for s in L:
    print(s * 2) # output: 2 4 20

The part to be repeated in the for loop has to be properly indented:

for elt in my_list:
    do_something
    something_else
print("loop finished") # outside the for block

Repeating a task

One typical use of a for loop is to repeat a certain task a fixed number of times:

n = 30
for iteration in range(n):
    do_something # this gets executed n times

Break and else

The for statement has two important keywords: break and

Get Scientific Computing with Python 3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.