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 else
. break
quits the for
loop even if the list we are iterating is not exhausted:
for x in x_values: if x > threshold: break print(x)
The finalizing else
checks whether the for
loop was broken
with the break
keyword. If it was not broken, the block following the else
keyword is executed:
for x in x_values: if x > threshold: break else: print("all the x are below the threshold")