for - loops

1. basic loops

Loops can be used to execute a block of code several times. The most commonly used loop is the for loop with the following syntax:

for value in iterable:
    # do things

iterable can be any series, e.g. a list, a tuple or a string:

for x in [3, 1.2, 'a']:
    print(x)
3
1.2
a
for letter in 'hello':
    print(letter)
h
e
l
l
o

Executing a code block n times

Sometimes we want a block of code to execute a certain amount of iterations. For this purpose we can use the range function:

for i in range(5):
    print(i)
0
1
2
3
4

Of course we don’t need to use the variable (in this case i) inside our code block:

n = 5
for i in range(n):
    print('some code to be executed ' + str(n) + ' times')
some code to be executed 5 times
some code to be executed 5 times
some code to be executed 5 times
some code to be executed 5 times
some code to be executed 5 times

We can also call the function with the arguments start, stop and (optionally) step:

for i in range(2, 10, 2):
    print(i)
2
4
6
8

Cancel a loop or skip steps

The break command can be used to stop a loop:

for i in range(100):
    if i > 3:
        break
    print(i)
0
1
2
3

The continue command only cancels the current step of the loop:

for i in range(4):
    if i == 1:
        continue
    print(i)
0
2
3

Creating lists with for loops

We can use for-loops to create lists. For that we have to write the for-loop inside square brackets [].

x = [element for element in 'an iterable']
print(x)
['a', 'n', ' ', 'i', 't', 'e', 'r', 'a', 'b', 'l', 'e']
# Another example with range:
x = [i for i in range(6)]
print(x)
[0, 1, 2, 3, 4, 5]

A very handy concept to work with lists in Python is called list comprehension. With the following syntax, an operation is applied to each element of the given series. A list with the computed elements is returned:

new_elements = [operation(element) for element in iterable]

Here, for example, the operation \(x^2\) is applied to all \(x \in [0,10]\):

[x**2 for x in range(11)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

2. looping texts

Now we are going short back to the Mattis’ Sequencing Notebook

text = '''
He Hazardous of we strong
follow bacteria walks
by town guy place
'''
print(text)
He Hazardous of we strong
follow bacteria walks
by town guy place
text_list = text.split(' ')
print(text_list)
['\nHe', 'Hazardous', 'of', 'we', 'strong\nfollow', 'bacteria', 'walks\nby', 'town', 'guy', 'place\n']
len(text_list)
10
for i in range(len(text_list)):
    print(i)
0
1
2
3
4
5
6
7
8
9
for i in range(len(text_list)):
    print(text_list[i])
He
Hazardous
of
we
strong
follow
bacteria
walks
by
town
guy
place
for i in range(len(text_list)):
    print(i, ' - ', text_list[i])
0  -  
He
1  -  Hazardous
2  -  of
3  -  we
4  -  strong
follow
5  -  bacteria
6  -  walks
by
7  -  town
8  -  guy
9  -  place

Another sometimes useful loop function is enumerate(). It iterates through a series and returns each value with the index of that value.

for index, value in enumerate(text_list):
    print(index, '\t', value)
0 	 
He
1 	 Hazardous
2 	 of
3 	 we
4 	 strong
follow
5 	 bacteria
6 	 walks
by
7 	 town
8 	 guy
9 	 place

3. Exercises

3.1 Typewriter Effect

try to make a for-loop to simulate an typewriter effect

# you'll need the following 2 libraries
from time import sleep
import sys

you will need 3 different functions to do that:

# sleep
# sys.stdout.write
# sys.stdout.flush

try to find out (remember the little-helpers) what you can do with them:

well…, we are using our text-string text to animate it:

text = '''
He Hazardous of we strong
follow bacteria walks
by town guy place
'''
print(text)
He Hazardous of we strong
follow bacteria walks
by town guy place

now, try to code the typewriter-effect (replace all pass with your code):

for letter in text:         # for each character in each line
    pass                    # 'print' a single character, and keep the cursor there.
    pass                    # 'sys.stdout.write' it into a buffer
    pass                    # 'sys.stdout.flush' the buffer
    pass                    # use 'sleep' to decide how many milliseconds will be between output each character
#hier 2-3 mögliche versionen...

for letter in text:
  sleep(0.05) # In seconds
  sys.stdout.write(letter)
  sys.stdout.flush()

for letter in text:
    print(letter, end='')
    sys.stdout.flush()
    sleep(0.05)
    
#hier wird der buffer direkt in print gesetzt:
for letter in text:
    print(letter, end='', flush=True)
    sleep(0.05)

H
e
 
H
a
z
a
r
d
o
u
s
 
o
f
 
w
e
 
s
t
r
o
n
g

f
o
l
l
o
w
 
b
a
c
t
e
r
i
a
 
w
a
l
k
s

b
y
 
t
o
w
n
 
g
u
y
 
p
l
a
c
e


H
e
 
H
a
z
a
r
d
o
u
s
 
o
f
 
w
e
 
s
t
r
o
n
g

f
o
l
l
o
w
 
b
a
c
t
e
r
i
a
 
w
a
l
k
s

b
y
 
t
o
w
n
 
g
u
y
 
p
l
a
c
e


H
e
 
H
a
z
a
r
d
o
u
s
 
o
f
 
w
e
 
s
t
r
o
n
g

f
o
l
l
o
w
 
b
a
c
t
e
r
i
a
 
w
a
l
k
s

b
y
 
t
o
w
n
 
g
u
y
 
p
l
a
c
e

try to humanize your output (a human being will not type on letter each millisecond)

# you will need the following library
from random import uniform
uniform?

replace the pass with your code:

for letter in text:
    print(letter, end='')
    sys.stdout.flush()
    pass

H
e
 
H
a
z
a
r
d
o
u
s
 
o
f
 
w
e
 
s
t
r
o
n
g

f
o
l
l
o
w
 
b
a
c
t
e
r
i
a
 
w
a
l
k
s

b
y
 
t
o
w
n
 
g
u
y
 
p
l
a
c
e

#hier wie's aussehen könnt...:
for letter in text:
    print(letter, end='')
    sys.stdout.flush()
    sleep(uniform(0, 0.3))

H
e
 
H
a
z
a
r
d
o
u
s
 
o
f
 
w
e
 
s
t
r
o
n
g

f
o
l
l
o
w
 
b
a
c
t
e
r
i
a
 
w
a
l
k
s

b
y
 
t
o
w
n
 
g
u
y
 
p
l
a
c
e

3.2 Dada Poem Generator

How to Make a Dadaist Poem

  • (method of Tristan Tzara)

# set variable
newspaper = """
Take a newspaper.
Take some scissors.
Choose from this paper an article of the length you want to make your poem.
Cut out the article.
Next carefully cut out each of the words that makes up this article and put them all in a bag.
Shake gently.
Next take out each cutting one after the other.
Copy conscientiously in the order in which they left the bag.
Them poem will resemble you.
And there you are – an infinitely original author of charming sensibility, even though unappreciated by the vulgar herd.""" 

print(newspaper)
Take a newspaper.
Take some scissors.
Choose from this paper an article of the length you want to make your poem.
Cut out the article.
Next carefully cut out each of the words that makes up this article and put them all in a bag.
Shake gently.
Next take out each cutting one after the other.
Copy conscientiously in the order in which they left the bag.
Them poem will resemble you.
And there you are – an infinitely original author of charming sensibility, even though unappreciated by the vulgar herd.

…remember the code from mattis’ sequencing-notebook:

import random
# Split string into list.
word_list = newspaper.split(' ')
# Shuffle list.
random.shuffle(word_list)
# Join list to string.
word_str = ' '.join(word_list)
print(word_str)
the after in vulgar original unappreciated bag.
Shake infinitely order a out makes other.
Copy the will article.
Next one the each conscientiously gently.
Next they poem.
Cut of some this all that even resemble poem to want cut this out newspaper.
Take 
Take charming and an up out take though by article herd. scissors.
Choose the you the – there each in words them of you.
And paper the from carefully cutting an which bag.
Them of make length the you are author article a your sensibility, left in put

now, try to make a for-loop out of it:

finally try to animate your cut-up: