For loops 1 - intro

Download exercises zip

Browse online files

If we want to perform some actions for each element of a collection, we will need the so-called for loop, which allows to iterate any sequence.

What to do

  1. Unzip exercises zip in a folder, you should obtain something like this:

for
    for1-intro.ipynb
    for1-intro-sol.ipynb
    for2-strings.ipynb
    for2-strings-sol.ipynb
    for3-lists.ipynb
    for3-lists-sol.ipynb
    for4-tuples.ipynb
    for4-tuples-sol.ipynb
    for5-sets.ipynb
    for5-sets-sol.ipynb
    for6-dictionaries.ipynb
    for6-dictionaries-sol.ipynb
    for7-nested.ipynb
    for7-nested-sol.ipynb
    for8-chal.ipynb
    jupman.py

WARNING: to correctly visualize the notebook, it MUST be in an unzipped folder !

  1. open Jupyter Notebook from that folder. Two things should open, first a console and then a browser. The browser should show a file list: navigate the list and open the notebook for1-intro.ipynb

  2. Go on reading the exercises file, sometimes you will find paragraphs marked Exercises which will ask to write Python commands in the following cells.

Shortcut keys:

  • to execute Python code inside a Jupyter cell, press Control + Enter

  • to execute Python code inside a Jupyter cell AND select next cell, press Shift + Enter

  • to execute Python code inside a Jupyter cell AND a create a new cell aftwerwards, press Alt + Enter

  • If the notebooks look stuck, try to select Kernel -> Restart

Iteration by element

If we have a sequence like this list:

[2]:
sports = ['volleyball', 'tennis', 'soccer', 'swimming']

and we want ito use every element of the list in some way (for example to print them), we can go through them (more precisely, iterate) with a for cycle:

[3]:
for element in sports:
    print('Found an element!')
    print(element)

print('Done!')
Found an element!
volleyball
Found an element!
tennis
Found an element!
soccer
Found an element!
swimming
Done!

Let’s see what happens in Python Tutor:

[4]:
# WARNING: FOR PYTHON TUTOR TO WORK, REMEMBER TO EXECUTE THIS CELL with Shift+Enter
#          (it's sufficient to execute it only once)

import jupman
[5]:
sports = ['volleyball', 'tennis', 'soccer', 'swimming']
for element in sports:
    print('Found an element!')
    print(element)

print('Done!')

jupman.pytut()
Found an element!
volleyball
Found an element!
tennis
Found an element!
soccer
Found an element!
swimming
Done!
[5]:
Python Tutor visualization

Names of variables in for

At each iteration, an element of the list is assigned to the variable element.

As variable name we can choose whatever we like, for example this code is totally equivalent to the previous one:

[6]:
sports = ['volleyball', 'tennis', 'soccer', 'swimming']
for name in sports:
    print('Found an element!')
    print(name)

print('Done!')
Found an element!
volleyball
Found an element!
tennis
Found an element!
soccer
Found an element!
swimming
Done!

We need to be careful about one thing:

II COMMANDMENT: Whenever you insert a variable in a for cycle, such variables must be new

If you defined the variable before, you shall not reintroduce it in a for, as this would bring confusion in the readers’ mind.

For example:

[7]:
sports = ['volleyball', 'tennis', 'soccer', 'swimming']
my_var = 'hello'

for my_var in sports:  # you lose the original variable
    print(my_var)

print(my_var) # prints 'swimming' instead of 'hello'
volleyball
tennis
soccer
swimming
swimming

Iterating strings

Strings are sequences of characters, so we can iterate them with for:

[8]:
for character in "hello":
    print(character)
h
e
l
l
o

Iterating tuples

Tuples are also sequences so we can iterate them:

[9]:
for word in ("I'm", 'visiting', 'a', 'tuple'):
    print(word)
I'm
visiting
a
tuple

Questions - iteration

Look at the following code fragments, and for each try guessing the result it produces (or if it gives an error):

  1. for i in [1,2,3]:
        print(i)
    
  2. for x in 7:
        print(x)
    
  3. for x in [7]:
        print(x)
    
  4. for x in ['a','b','c']:
        x
    
  5. for i in []:
        print('GURB')
    
  6. for i in [1,2,3]:
        print(type(i))
    
  7. for i in '123':
        print(type(i))
    
  8. for i in 'abc':
        print(i)
    
  9. for x in ((4,5,6)):
        print(x)
    
  10. for x in [[1],[2,3],[4,5,6]]:
        print(x)
    
  11. x = 5
    for x in ['a','b','c']:
        print(x)
    print(x)
    
  12. for x in ['a','b','c']:
        pass
    print(x)
    
  13. for x in [1,2,3,4,5,6,7,8]:
        if x % 2 == 0:
            print(x)
    
  14. la = [4,5,6]
    for x in la:
        print(x)
    la.reverse()
    for x in la[1:]:
        print(x)
    

Exercise - magic carpet

✪ Months ago you bought a carpet from a pitchman. After some time, after a particularly stressful day, you say ‘I wish I went on vacation to some exotic places, like say, Marrakesh!’ To your astonishment, the carpet jumps in the air and answers: ‘I hear and obey!’

Write some code which given the lists of places trip1 and trip2 prints all the visited stops.

Example - given:

trip1 = ['Marrakesh','Fez','Bazaar','Kasbah']
trip2 = ['Koutoubia', 'El Badii', 'Chellah']

Prints:

The first trip starts
      You: Let's go to Marrakesh !
   Carpet: I hear and obey
      You: Let's go to Fez !
   Carpet: I hear and obey
      You: Let's go to Bazaar !
   Carpet: I hear and obey
      You: Let's go to Kasbah !
   Carpet: I hear and obey
End of second trip

The second trip starts
      You: Let's go to Koutoubia !
    Carpet: I hear and obey
      You: Let's go to El Badii !
    Carpet: I hear and obey
      You: Let's go to Chellah !
    Carpet: I hear and obey
End of second trip
Show solution
[10]:

trip1 = ['Marrakesh','Fez','Bazaar','Kasbah'] trip2 = ['Koutoubia', 'El Badii', 'Chellah'] # write here

Esercise - evensum

✪ Given the list numbers, write some code which calculates and prints the sum of the even elements (not the elements at even indexes !)

Example - given:

numbers = [3,4,1,5,12,7,9]

finds 4 and 12 so it must print:

16
Show solution
[11]:

numbers = [3,4,1,5,12,7,9] # write here

Exercise - birbantello

✪ Given a string in lowercase, write some code which prints each character in uppercase followed by the character as lowercase.

  • HINT: to obtain uppercase characters use the .upper() method

Example - given:

s = "birbantello"

Prints:

B b
I i
R r
B b
A a
N n
T t
E e
L l
L l
O o
Show solution
[12]:

s = "birbantello" # write here

Exercise - articulate

✪ A new word is taught to a kid. He knows a lot of characters from the alphabet, but not all of them. To remember the known ones, he treats them as they where actors divided in three categories: the good, bad ad ugly. Write some code which given a word prints all the characters and for each of them tells whether it is good, bad or ugly. If a character is not recognized by the kid, prints ‘not interesting’.

Example - given:

word = 'articulate'

good = 'abcde'
bad = 'ru'
ugly = 'ijklmn'

Prints:

a is good
r is bad
t is not interesting
i is ugly
c is good
u is bad
l is ugly
a is good
t is not interesting
e is good
Show solution
[13]:

word = 'articulate' good = 'abcde' bad = 'ru' ugly = 'ijklmn' # write here

Exercise - gala

✪ At a gala event, many high-society people are invited. At the beginning of the evening, doors are opened and guests enter a queue. Unfortunately, during these occasions uninvited guests always show up, so the concierge in the atrium is given a list of unwelcome ones. Whenever a guest is recognized as unwelcome, he will be taken care by the strong hands of Ferruccio the bouncer. Illustrious guests will be written instead in the list admitted.

Write some code which prints the various passages of the event.

Example - given:

queue = ['Consul','Notary','Skeleton','Dean','Goblin','Vampire', 'Jeweller']
unwelcome = {'Vampire','Goblin','Skeleton'}
admitted = []

Prints:

Open the doors!

Good evening Mr Consul
  This way, Your Excellence
  Next in line !
Good evening Mr Notary
  This way, Your Excellence
  Next in line !
Good evening Mr Skeleton
  Ferruccio, would you please take care of Mr Skeleton ?
  Next in line !
Good evening Mr Dean
  This way, Your Excellence
  Next in line !
Good evening Mr Goblin
  Ferruccio, would you please take care of Mr Goblin ?
  Next in line !
Good evening Mr Vampire
  Ferruccio, would you please take care of Mr Vampire ?
  Next in line !
Good evening Mr Jeweller
  This way, Your Excellence
  Next in line !

These guests were admitted: Consul, Notary, Dean, Jeweller
Show solution
[14]:

queue = ['Consul','Notary','Skeleton','Dean','Goblin','Vampire', 'Jeweller'] unwelcome = {'Vampire','Goblin','Skeleton'} admitted = [] # write here

Exercise - balance

✪✪ A crop of seeds has been harvested, and seeds will be poured in a certain number of bags of a given capacity each (i.e. 15 kilograms).

The seeds arrive in containers of variable capacity. Each container is placed on a weight scale and its content is poured in the current bag. As soon as the quantity capacity is reached, the scale weight is emptied, the bag is substituted with a new one which starts being filled from what remains from the previous fill. Write some code which prints the procedure.

Example - given:

containers = [5,1,7,4,3,9,5,2,7,3]
capacity = 15

Prints:

Take 5 kg
The scale weight shows 5 kg
Take 1 kg
The scale weight shows 6 kg
Take 7 kg
The scale weight shows 13 kg
Take 4 kg
The scale weight shows 17 kg
We reached the capacity of 15 kg, there remain 2 kg

Take 3 kg
The scale weight shows 5 kg
Take 9 kg
The scale weight shows 14 kg
Take 5 kg
The scale weight shows 19 kg
We reached the capacity of 15 kg, there remain 4 kg

Take 2 kg
The scale weight shows 6 kg
Take 7 kg
The scale weight shows 13 kg
Take 3 kg
The scale weight shows 16 kg
We reached the capacity of 15 kg, there remain 1 kg

We filled 3 bags
Show solution
[15]:

containers = [5,1,7,4,3,9,5,2,7,3] capacity = 15 # write here

Counting with range

If we need to keep track of the iteration number, we can use the iterable sequence range, which produces a series of integer numbers from 0 INCLUDED until the specified number EXCLUDED:

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

Note it did not print the limit 5

When we call range we can also specify the starting index, which is INCLUDED in the generated sequence, while the arrival index is always EXCLUDED:

[17]:
for i in range(3,7):
    print(i)
3
4
5
6

Counting intervals: we can specify the increment to apply to the counter at each iteration by passing a third parameter, for example here we specify an increment of 2 (note the final 18 index is EXCLUDED from the sequence):

[18]:
for i in range(4,18,2):
    print(i)
4
6
8
10
12
14
16

Reverse order: we can count in reverse by using a negative increment:

[19]:
for i in range(5,0,-1):
    print(i)
5
4
3
2
1

Note how the limit 0 was not reached, in order to arrive there we need to write

[20]:
for i in range(5,-1,-1):
    print(i)
5
4
3
2
1
0

Questions - range

Look at the following code fragments, and for each try guessing the result it produces (or if it gives an error):

  1. for x in range(1):
        print(x)
    
  2. for i in range(3):
        i
    
  3. for i in range(3):
    print(i)
    
  4. for x in range(-1):
        print(x)
    
  5. for 'm' in range(3):
        print('m')
    
  6. for i in range(3):
        i-1
    
  7. for x in range(6,4,-1):
        print(x)
    
  8. for x in range(1,0,-1):
        print(x)
    
  9. for x in range(3,-3,-2):
        print(x)
    
  10. for x in 3:
        print(x)
    
  11. x = 3
    for i in range(x):
        print(i)
    for i in range(x,2*x):
        print(i)
    
  12. for x in range(range(3)):
        print(x)
    

Exercise - printdoubles

✪ Given a positive number n (i.e. n=4) write some code which prints:

The double of 0 is 0
The double of 1 is 2
The double of 2 is 4
The double of 3 is 6
Show solution
[21]:

n = 4 # write here

Exercise - multiples or not

✪✪ Write some code which given two integer positive numbers k and b:

  • first prints all the numbers from k INCLUDED to b INCLUDED which are multiples of k

  • the prints all the numbers from k EXCLUDED to b EXCLUDED which are NOT multiples of k

Example - given:

k,b = 3,15

it prints:

Multiples of 3
3
6
9
12
15

Not divisible by 3
4
5
7
8
10
11
13
14
Show solution
[22]:

k,b = 3,15 # write here

Exercise - ab interval

✪✪ Given two integers a and b greater or equal than zero, write some code which prints all the integer numbers among the two bounds INCLUDED.

  • NOTE: a may be greater, equal or less than b, your code must handle all the cases.

Example 1 - given:

a,b = 5,9

it must print:

5
6
7
8
9

Example 2 - given:

a,b = 8,3

it must print:

3
4
5
6
7
8
Show solution
[23]:

a,b = 5,9 # 5 6 7 8 9 #a,b = 8,3 # 3 4 5 6 7 8 #a,b = 6,6 # 6 # write here

Exercise - FizzBuzz

Write some code which prints the numbers from 1 to 35 INCLUDED, but when a number is divisible by 3 prints instead FIZZ, when it is divisible by 5 prints BUZZ, and when it is divisible by 3 and 5 prints FIZZBUZZ.

Expected output:

1
2
FIZZ
4
BUZZ
FIZZ
7
8
FIZZ
BUZZ
11
FIZZ
13
14
FIZZBUZZ
16
17
FIZZ
19
BUZZ
FIZZ
22
23
FIZZ
BUZZ
26
FIZZ
28
29
FIZZBUZZ
31
32
FIZZ
34
BUZZ
Show solution
[24]:


# write here

Iterating by index

If we have a sequence like a list, sometimes during the iteration it is necessary to know in which cell position we are. We can generate the indexes with range, and use them to access a list:

[25]:
sports = ['volleyball', 'tennis', 'soccer', 'swimming']

for i in range(len(sports)):
    print('position', i)
    print(sports[i])
position 0
volleyball
position 1
tennis
position 2
soccer
position 3
swimming

Note we passed to range the dimension of the list obrained with len.

Exercise - kitchen

✪ Write some code which given a list of an even number of strings kitchen, prints the couples of elements we can find in sequences, one row at a time

Example - given:

kitchen = ['oil', 'soup', 'eggs', 'pie', 'tomato sauce', 'pasta', 'meat sauce', 'lasagna']

Prints:

oil, soup
eggs, pie
tomato sauce, pasta
meat sauce, lasagna
Show solution
[26]:

kitchen = ['oil', 'soup', 'eggs', 'pie', 'tomato sauce', 'pasta', 'meat sauce', 'lasagna'] # write here

Exercise - neon

✪ Given two lists la and lb of equal length \(n\), write some code which prints their characters separated by a space on \(n\) rows

Example - given:

la = ['n','e','o','n']
lb = ['s','h','o','w']

prints:

n s
e h
o o
n w
Show solution
[27]:

la = ['n','e','o','n'] lb = ['s','h','o','w'] # write here

Exercise - emotions

✪ Given the list of strings emotions and another one grade containing the numbers -1 and 1, write some code which prints the emotions followed with ‘positive’ if their corresponding grade is a number greater than zero or ‘negative’ otherwise

Example - given:

emotions = ['Fear', 'Anger','Sadness','Joy','Disgust','Ecstasy']
grade =    [-1,       -1,     -1,       1,     -1,        1]

prints:

Fear : negative
Anger : negative
Sadness : negative
Joy : positive
Disgust : negative
Ecstasy : positive
Show solution
[28]:

emotions = ['Fear', 'Anger','Sadness','Joy','Disgust','Ecstasy'] grade = [-1, -1, -1, 1, -1, 1] # write here

Exercise - organetto

✪ Given a string s, write some code which prints all the substrings you can obtain from the position of the character 'n' and which terminates with the last character of s.

Example - given:

s = 'organetto'

Prints:

netto
etto
tto
to
o
Show solution
[29]:

s = 'organetto' # write here

Exercise - sghiribizzo

Write some code which given the string s prints all the possible combinations of row couples such that a row begins with the first characters of s and the successive continues with the following characters.

Example - given:

s = 'sghiribizzo'

prints:

s
 ghiribizzo
sg
  hiribizzo
sgh
   iribizzo
sghi
    ribizzo
sghir
     ibizzo
sghiri
      bizzo
sghirib
       izzo
sghiribi
        zzo
sghiribiz
         zo
sghiribizz
          o
sghiribizzo
Show solution
[30]:

s = 'sghiribizzo' # write here

Exercise - dna

Given two DNA strings s1 and s2 of equal length, write some code which prints among the first and second string another string made by spaces ` ` and pipe \(|\) where equal characters are found.

  • HINT: create a list containing the characters space or the character \(|\), and only at the end convert the string by using strings join method (doing so is much more efficient than keep generating strings with + operator)

Example - given:

s1 = "ATACATATAGGGCCAATTATTATAAGTCAC"
s2 = "CGCCACTTAAGCGCCCTGTATTAAAGTCGC"

Prints:

ATACATATAGGGCCAATTATTATAAGTCAC
   ||  || |  |  |   |  ||||| |
CGCCACTTAAGCGCCCTGTATTAAAGTCGC
Show solution
[31]:

s1 = "ATACATATAGGGCCAATTATTATAAGTCAC" s2 = "CGCCACTTAAGCGCCCTGTATTAAAGTCGC" # write here

Exercise - sportello

✪✪ Given a string s, prints the first half of the characters as lowercase and the following half as uppercase.

  • if the string is of odd length, the first half must have one character more than the second string.

Example - given:

s = 'sportello'

Your code must print:

s
p
o
r
t
E
L
L
O

(note that ‘sportello’ has odd length and there are five characters in the first half and four in the second

Show solution
[32]:

s = 'sportello' # sportELLO #s = 'maglia' # magLIA # write here

Exercise - farm

✪✪ Given a dictionary sounds which associates animal names to the sounds they produce, and a list rooms of tuples of 2 elements containing the animal names, write some code that for each room prints the sounds you hear while passing in front of it.

  • NOTE: the rooms to print are numbered from 1

Example - given:

sounds = {'dog':'Bark!',
          'cat':'Mew!',
          'cow':'Moo!',
          'sheep':'Bleat!'}

rooms = [('dog', 'sheep'),
         ('cat','cow'),
         ('cow', 'dog')]

Prints:

In the room 1 we hear Bark! and Bleat!
In the room 2 we hear Mew! and Moo!
In the room 3 we hear Moo! and Bark!
Show solution
[33]:

sounds = {'dog':'Bark!', 'cat':'Mew!', 'cow':'Moo!', 'sheep':'Bleat!'} rooms = [('dog', 'sheep'), ('cat','cow'), ('cow', 'dog')] # write here

Exercise - pokemon

✪✪✪ Given a list pokemon and a number g of groups, write some code which prints g rows showing all the group components. Group the pokemons in the order you find them in the list.

  • HINT 1: To obtain the number of group components you should use integer division //

  • HINT 2: to print group components use the method join of strings

Example 1 - given:

#               0         1          2         3            4         5
pokemon = ['Charizard','Gengar','Arcanine','Bulbasaur','Blaziken','Umbreon',
#               6         7          8         9           10          11
           'Lucario','Gardevoir','Eevee','Dragonite', 'Volcarona', 'Sylveon' ]
g = 3

prints:

group 1 : Charizard and Gengar and Arcanine and Bulbasaur
group 2 : Blaziken and Umbreon and Lucario and Gardevoir
group 3 : Eevee and Dragonite and Volcarona and Sylveon

Example 2 - given:

#               0         1          2         3            4         5
pokemon = ['Charizard','Gengar','Arcanine','Bulbasaur','Blaziken','Umbreon',
#               6         7          8         9           10          11
           'Lucario','Gardevoir','Eevee','Dragonite', 'Volcarona', 'Sylveon' ]

g = 4

prints:

group 1 : Charizard and Gengar and Arcanine
group 2 : Bulbasaur and Blaziken and Umbreon
group 3 : Lucario and Gardevoir and Eevee
group 4 : Dragonite and Volcarona and Sylveon
Show solution
[34]:

# 0 1 2 3 4 5 pokemon = ['Charizard','Gengar','Arcanine','Bulbasaur','Blaziken','Umbreon', # 6 7 8 9 10 11 'Lucario','Gardevoir','Eevee', 'Dragonite', 'Volcarona', 'Sylveon' ] g = 3 #g = 4 # write here

Modifying during iteration

Suppose you have a list la containing characters, and you are asked to duplicate all the elements, for example if you have

lst = ['a','b','c']

after your code it must result

>>> print(lst)
['a','b','c','a','b','c']

Since you gained such great knowledge about iteration,you might be tempted to write something like this:

for char in lst:
    lst.append(char)    # WARNING !

QUESTION: Do you see any problem?

Show answer

X COMMANDMENT: You shall never ever add nor remove elements from a sequence you are iterating with a for !

Falling into such temptations would produce totally unpredictable behaviours (do you know the expression pulling the rug out from under your feet ? )

What about removing? We’ve seen that adding is dangerous, but so is removing. Suppose you have to eliminate all the elements from a list, you might be tempted to write something like this:

[35]:
my_list = ['a','b','c','d','e']

for el in my_list:
    my_list.remove(el)   # VERY BAD IDEA

Have a close look at the code. Do you think we removed everything, uh?

[36]:
my_list
[36]:
['b', 'd']

O_o' The absurd result is given by the internal implementation of Python, our version of Pyhton gives this result, yours might give a completely different one. So be careful!

If you really need to remove elements from a sequence you are iterating, use a while cycle or duplicate first a copy of the original sequence.

Exercise - duplicate

✪ Try writing some code which MODIFIES a list la by duplicating the elements

  • use a for cycle

  • DO NOT use list multiplication

Example - given:

la = ['a','b','c']

after your code, it must result:

>>> la
['a','b','c','a','b','c']
Show solution
[37]:

la = ['a','b','c'] # write here

Exercise - hammers

✪ Given a list of characters la, MODIFY the list by changing all the characters at even indeces with the character z

Example - given:

la = ['h', 'a', 'm', 'm', 'e', 'r', 's']

after your code, it must result:

>>> print(la)
['z', 'a', 'z', 'm', 'z', 'r', 'z']
  • NOTE: here we are not adding nor removing cells from the list

Show solution
[38]:

la = ['h', 'a', 'm', 'm', 'e', 'r', 's'] # write here

Exercise - Orangutan

✪✪ Given two strings sa and sb, write some code which places in the string sc a string composed by alternating all the characters in sa and sb.

  • if a string is shorter than the other one, at the end of sc put all the remaining characters from the other string.

  • HINT: even if it is possible to augment a string a character at a time at each iteration, each time you do so a new string is created (because strings are immutable). So it’s more efficient to keep augmenting a list, and then convert to string only at the very end.

Example - given:

sa,sb = 'gibbon', 'ORANGUTAN'

after your code it must result:

>>> print(sc)
gOiRbAbNoGnUTAN
Show solution
[39]:

sa,sb = 'gibbon', 'ORANGUTAN' # gOiRbAbNoGnUTAN #sa,sb = 'cruise ship', 'BOAT' # cBrOuAiTse ship # write here

Exercise - basket

✪✪✪ There is a basket full of fruits, which we represent as a list of strings. We want to take all the fruits and put them in a plate, in the same order we find them in the basket. We must take only the fruits contained in the set preferences.

  • The basket may contain duplicates, if they are in the preferences you must take them all

  • the fruits are to be taken in the same order in which they were found

Example - given:

basket = ['strawberry', 'melon', 'cherry', 'watermelon', 'apple', 'melon','watermelon', 'apple', ]
preferences = {'cherry', 'apple', 'strawberry'}
plate = []

after your code, it must result:

>>> print(basket)
['melon', 'watermelon', 'melon', 'watermelon']
>>> print(plate)
['strawberry', 'cherry', 'apple', 'apple']

You can solve the problem in two ways:

  • Way 1 (simple and recommended): create a list new_basket and finally assign the variable basket to it

  • Way 2 (hard, slow, not recommended but instructive): MODIFY the original basket list, using the pop method and without ever reassigning basket, so no rows beginning with basket =

Try solving the exercise in both ways.

Either way, always remember the sacred X COMMANDMENT:

You shall never ever add nor remove elements from a sequence you are iterating with a for !

Show solution
[40]:

# WAY 1 basket = ['strawberry', 'melon', 'cherry', 'watermelon', 'apple', 'melon','watermelon', 'apple', ] preferences = {'cherry', 'apple', 'strawberry'} plate = [] # write here

Show solution
[41]:

# WAY 2 basket = ['strawberry', 'melon', 'cherry', 'watermelon', 'apple', 'melon','watermelon', 'apple', ] preferences = {'cherry', 'apple', 'strawberry'} plate = [] # write here

break and continue commands

We can use the commands break and continue to have even more control on loop execution.

NOTE: Please use sparingly!

When there is a lot of code in the cycle it’s easy to ‘forget’ about their presence and introduce hard-to-discover bugs. On the other hand, in some selected cases these commands may increase code readability, so as everything use your judgement.

Terminate with break

To immediately exit a cycle you can use the break command:

[42]:
for x in 'PARADE':

    if x == 'D':
        print('break, exits the loop!')
        break
        print('After the break')

    print(x)

print('Loop is over !')
P
A
R
A
break, exits the loop!
Loop is over !

Note how the instruction which prints 'After the break' was not executed

Jumping with continue

By calling continue execution is immediately brough to the next iteration , so we jump to the next element in the sequence without executing the instructions after the continue.

[43]:
i = 1
for x in 'PARADE':
    if x == 'A':
        print("continue, jumps to next element")
        continue
    print(x)
print('Loop is over !')
P
continue, jumps to next element
R
continue, jumps to next element
D
E
Loop is over !

Combining break and continue

Let’s see both in Python Tutor:

[44]:
i = 1
for x in 'PARADE':
    if x == 'A':
        print("continue, jumps to next element")
        continue
    if x == 'D':
        print('break, exits loop!')
        break
    print(x)

print('Loop is over !')

jupman.pytut()
P
continue, jumps to next element
R
continue, jumps to next element
break, exits loop!
Loop is over !
[44]:
Python Tutor visualization

Questions - break and continue

Look at the following code fragments, and for each try guessing the result it produces (or if it gives an error):

  1. for x in ['a','b','c']:
        print(x)
        break
    
  2. for x in ['a','b','c']:
        print(x)
        break
        print('GLAM')
    
  3. for x in ['a','b','c']:
        print(x)
        break
        break
    
  4. for x in ['a','b','c']:
        break
        print(x)
    
  5. break
    for x in ['a','b','c']:
        print(x)
    
  6. for x in ['a','b','c']:
        print(x)
    break
    
  7. for x in ['a','b','c']:
        continue
        print(x)
    
  8. for x in ['a','b','c']:
        print(x)
        continue
    
  9. for x in ['a','b','c']:
        print(x)
        continue
        print('BAM')
    
  10. continue
    for x in ['a','b','c']:
        print(x)
    
  11. for x in ['a','b','c']:
        print(x)
    continue
    
  12. for x in ['a','b','c']:
        break
        1/0
    print('BAD KARMA')
    
  13. for x in ['a','b','c']:
        1/0
        break
    print('BAD KARMA')
    
  14. for x in range(8):
        if x < 4:
            continue
        print('ZAM', x)
    
  15. for x in range(8):
        if x >= 4:
            break
        print('ZUM', x)
    
  16. for x in range(6):
        if x % 2 == 0:
            continue
        print(x)
    
  17. for x in ['M','C','M']:
        print(x)
        for y in ['S','P','Q','R']:
            print(y)
            break
    
  18. for x in ['M','C','M']:
        print(x)
        break
        for y in ['S','P','Q','R']:
            print(y)
    
  19. for x in ['M','C','M']:
        print(x)
        for y in ['S','P','Q','R']:
            print(y)
            continue
    
  20. for x in ['M','C','M']:
        print(x)
        continue
        for y in ['S','P','Q','R']:
            print(y)
    

Exercise - autonomous walking

✪ Write some code which given a string phrase, prints all the characters except the vocals.

Example - given:

phrase = 'autonomous walking'

prints:

t
n
m
s

w
l
k
n
g
Show solution
[45]:

phrase = 'autonomous walking' #phrase='continuous' # write here

Exercise - breaking bad

✪ Write some code which prints all the charactes from string until it finds the string 'bad'.

Example - given:

string = 'cascapirillabadgnippobadzarpogno'

prints

c
a
s
c
a
p
i
r
i
l
l
a
Show solution
[46]:

string = 'cascapirillabadgnippobadzarpogno' # cascapirilla #string = 'sobad' # 'so' #string = 'bad' # '' #string = 'badso' # '' # write here

Exercise - breaking point

✪✪ Given a phrase, prints all the words one per row until it finds a dot, and in that case it stops.

  • DO NOT use phrase.split('.'). Splits on other characters are allowed.

Example - given:

phrase = 'At some point you must stop. Never go beyond the limit.

prints:

At
some
point
you
must
stop
Show solution
[47]:

phrase = 'At some point you must stop. Never go beyond the limit.' #phrase = "Respect the halt. Do you want to have us arrested?" #phrase = 'Stop.' #phrase = 'No stop' # write here

Exercise - breakdance

✪✪ As a skilled breakdancer, you’re given music as a list of sounds. You will have to perform a couple of dances:

  • during the first one, you will have to repeat the music sounds until you find exactly 3 sounds 'pa', then you will shout BREAKDANCE!.

  • during the second one, you will have to repeat the music sounds in reverse until you find exactly 3 sounds 'pa', then you will shout BREAKDANCE!

  • DO NOT modify music, so no music.reverse()

Example - given:

music = ['unz','pa','pa','tud','unz','pa','pa','tud','unz','boom','boom','tud']

Prints:

unz
pa
pa
tud
unz
pa
BREAKDANCE!

tud
boom
boom
unz
tud
pa
pa
unz
tud
pa
BREAKDANCE!
Show solution
[48]:
music = ['unz','pa','pa','tud','unz','pa','pa','tud','unz','boom','boom','tud']

# write here


unz
pa
pa
tud
unz
pa
BREAKDANCE!

tud
boom
boom
unz
tud
pa
pa
unz
tud
pa
BREAKDANCE!

Continue

Go on with exercises on iterating strings