Loops#

If we want to do something multiple times, we can use loops. In Python, we have two types of loops: for and while.

For Loop#

This type of loop is used to iterate over a sequence (list, tuple, string, etc.) and execute a block of code for each item in the sequence. Or to repeat a block of code a specific number of times. Imagine wanting to do something for each item in a list:

a = [1, 2, "l", 4, 5, "a", "b", "c"]

for element in a:
    print(element)
1
2
l
4
5
a
b
c

TASK: print for each number in the list a if it is even or odd. If you encounter a string, print “This is a string”.

If we want to do something a specific number of times, we can use the range function:

for i in range(5): #this equals to range(0, 5)
    print(i)
0
1
2
3
4

REMEMBER: the range function starts at 0 and ends at the number before the one you specify. TASK: print the numbers from 10 to 20.

If we want to iterate over a list and also get the index of the current item, we can use the enumerate function:

for index, element in enumerate(a):
    print(index, element)
0 1
1 2
2 l
3 4
4 5
5 a
6 b
7 c

Nested For Loops#

We can also have loops inside loops. This is useful when iterating a multi-dimensional data structure, like a matrix.

import numpy as np
ranM = np.random.randint(0, 10, (3, 3))

print(ranM)

for row in ranM:
    for element in row:
        print(element)
[[5 2 9]
 [1 3 6]
 [3 6 2]]
5
2
9
1
3
6
3
6
2

While Loop#

This type of loop is used to repeat a block of code as long a condition is fulfilled (== True). IMPORTANT: Be careful with while loops, they can run forever if the condition is never met. IMPORTANT: We check the condition at the beginning of the loop, so if the condition is not met, the loop will not run at all.

#imagine we want to add a character to a string until it reaches a certain length
#additionally we want to get the number of characters we added

string = "a"
counter = 0

while len(string) < 10: #here we encounter two new things: len() and the += operator
    string += "h"
    counter += 1

print(string)
print(counter)
ahhhhhhhhh
9

Break#

Sometimes we want to stop the loop before it finishes. For this we can use the break statement.

while(True):
    print("This can run forever")
    if input("Do you want to stop? (y/n)") == "y": #input() is a function that waits for user input
        break
This can run forever

TASK: Run through each item of the list a (the one we already used) and stop the loop when you encounter a string. There are multiple ways to do this.

Continue#

Sometimes we want to skip the rest of the code in the loop and start the next iteration. For this we can use the continue statement. This comes in handy, if we want to iterate through files for example and skip the ones that are not of interest.

for i in range(10): #what happens here?
    if i % 2 == 0:
        continue
    print("hello")
hello
hello
hello
hello
hello

Pass#

Sometimes we want to have an empty loop or function. For this we can use the pass statement. This can be useful when we are not sure what to put in the loop yet, but we want to have it there.

for i in range(10): 
    pass
print(i)
9

Comprehensions#

Comprehensions are a way to create lists, dictionaries or sets in a more concise way. They are very useful. Here we will only look at list comprehensions. This is how we can use a for loop to create a list:

a = [i for i in range(10)]
print(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

We can even add an if statement when iterating:

a = [i for i in range(10) if i % 2 == 0]
print(a)
[0, 2, 4, 6, 8]

We can perform operations on the elements we iterate over:

a = [i**2 for i in range(10)]
print(a)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

The topic of comprehensions is very broad and we will not go into more detail here. But you should know that they exist and are very useful. So don’t be surprised if you encounter them in code.