While and For Loops

NoteLoops?!

Oftentimes, we write Python statements that repeat the same task — i.e. they loop a certain number of times or over multiple items.

NoteHow do I write loops in Python?

Using for and while statements.

NoteWhat is the difference between for and while statements?

The while statement provides a way to code general loops. The for statement is designed for stepping through the items in a sequence or other iterable object and running a block of code for each.

# loop until reaching a numeric threshold
>>> i = 0
>>> while i <= 3:
...     print(i)
...     i = i + 1
0
1
2
3

# loop until an empty string is returned
>>> x = "Indiana Jones"
>>> while x != "":
...     print(x)
...     x = x[1:]
...
Indiana Jones
ndiana Jones
diana Jones
iana Jones
ana Jones
na Jones
a Jones
 Jones
Jones
ones
nes
es
s
NoteCan you give an example of a while loop?

while statements run a code block insofar as a test evaluates to True. In the upper section of Example 4.31, we assign a i to a number. Then we create a for loop with the following elements: the first one is a statement testing whether i is smaller or equal to 3 (see line 3); the second element is the loop body (indented), which is repeated as long as the test evaluates to True. It is worth noticing that every iteration of the loop body produces a unitary increase in i — the program leaves the loop after four iterations. In the lower section of Snippet 4.31, we assign the variable x to a string (line 13), which we eventually print (line 14) and slice (line 15) until we get an empty string (line 13x).

NoteCan you give an example of a for loop?

for steps through a sequence of items and carries out a task. In the upper section of Snippet 4.32, we print the result of a mathematical operation deployed over the items of a list (an example of a Python iterable object). The code included in line 2 assigns the variable item to an element of iterable temporarily. Then, the code block (indented) is executed over the temporary object. In the lower section of Snippet 4.32, the execution of the loop operates a mathematical expression over the items of a first list and appends the outcome to a second list (line 10).

# print the result of a mathematical operation carried out over a list of items
>>> for item in [0, -99, 13, 6.54]:
...     print(item ** 0.5)
0.0
(6.092540900222253e-16+9.9498743710662j)
3.605551275463989
2.5573423705088842
# run a mathematical operation on a list of items and append the outcome
# to a second list
>>> input = [2, 8, 1]
>>> output = []
>>> for item in input:
...    output.append(item + 1)
>>> print(output)
[3, 9, 2]
NoteHow do I use for loops with dictionaries?

Like lists, dictionaries are iterable objects. In the upper section of Snippet 4.33, we create a dictionary and iterate over its items printing a simple predicate. As we know from the dictionaries section, we access a dictionary’s values by keys. Hence, in line 5, we retrieve the keys of D. Then, in line 12, we fetch the value of the temporary object k, namely, D[k]. Particularly, we print the temporary object k, the string object IS, and the value associated with k; that is, D[k]. In Snippet 34, we accomplish the same task of Snippet 33. However, the loop regards a dictionary’s items — i.e., key-value pairs — instead of keys (that is self-evident from the comparison of Snippet 33’s line 55 and Snippet 34’s line 5).

# the dictionary
>>> D = {"Thor": "Asgardian", "Vision": "android", "Wanda Maximoff": "human"}

# get the keys of D
>>> keys = D.keys()
>>> print(keys)
dict_keys(['Thor', 'Vision', 'Wanda Maximoff'])

# iterate over the keys to fetch the dictionary values and do something
# with them
>>> for k in keys:
...     print(k + " IS " + D[k])
Thor IS Asgardian
Vision IS android
Wanda Maximoff IS human
# the dictionary
>>> D = {"Thor": "Asgardian", "Vision": "android", "Wanda Maximoff": "human"}

# get the items of D
>>> items = D.items()

# iterate over key-value pairs and do something with them
>>> for k, v in items:
...    print(k + " IS " + v)
Thor IS Asgardian
Vision IS android
Wanda Maximoff IS human
NoteWhy are counter for loops so popular?

The built-in class range provides an immutable sequence that is particularly helpful for loops that repeat an action a certain number of times. Snippet 35 shows an example of a for loop with range.

# show the outcome of range
>>> list(range(3))
[0, 1, 2]

# use range in a for loop
>>> for i in range(3):
...     print(i, ":-)")
0 :-)
1 :-)
2 :-)
NoteWhat is a nested for loop?

A Python statement that contains multiple for loops is a nested for loop. Mainly, a for loop allows to jointly carry out a task over the elements of two iterables. The outer loop considers the individual items of the first iterable (see Snippet 4.26, line 6); the inner loop (indented) considers the individual items of the second list (see line 7). Once we have created a pair of temporary objects, we can do something with it (see line 8).

# the lists
>>> LETTERS = ["x", "y", "z"]
>>> COLORS = ["blue", "green", "red"]

# create all permutations of letters and colors and print them
>>> for i in LETTERS:
...     for j in COLORS:
...         print(i, " <-> ", j)
x  <->  blue
x  <->  green
x  <->  red
y  <->  blue
y  <->  green
y  <->  red
z  <->  blue
z  <->  green
z  <->  red
NoteNested for loops Vs. zip for loops?

Contrarily to the nested for loops, which considers all permutations containing multiple iterables’ items, the built-in zip steps through several iterables in parallel, producing tuples with an item from each one. As shown in Snippet 4.37, there is neither an inner nor an outer for loop in this case — instead, there is a single loop considering two temporary objects, i and j, that occupy the same position in the offset of the iterables at hand (see line 6; the first item from the first iterable goes with the first item from the second iterable, the second item from the first iterable goes with the second item from the second iterable, and so on).

# the lists
>>> LETTERS = ["x", "y", "z"]
>>> COLORS = ["blue", "green", "red"]

# create one-to-one matches of items and do something with them
>>> for i, j in zip(LETTERS, COLORS):
...     print(i, " <-> ", j)
x  <->  blue
y  <->  green
z  <->  red