Conditionals - for loops

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:

control-flow
    flow1-if.ipynb
    flow1-if-sol.ipynb
    flow2-for.ipynb
    flow2-for-sol.ipynb
    flow3-while.ipynb
    flow3-while-sol.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 flow2-for.ipynb

  2. Go on reading the exercises file, sometimes you will find paragraphs marked Exercises graded from ✪ to ✪✪✪✪ 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 exemple 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]:

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


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

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


16

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


B b
I i
R r
B b
A a
N n
T t
E e
L l
L l
O o

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


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

Exercise - gala

✪ At a gala event 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


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

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


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

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


The double of 0 is 0
The double of 1 is 2
The double of 2 is 4
The double of 3 is 6

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


Multiples of 3
3
6
9
12
15

Not divisible by 3
4
5
7
8
10
11
13
14

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


5
6
7
8
9

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:

[24]:
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
[25]:
kitchen = ['oil', 'soup', 'eggs', 'pie', 'tomato sauce', 'pasta', 'meat sauce', 'lasagna']

# write here


oil, soup
eggs, pie
tomato sauce, pasta
meat sauce, lasagna

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
[26]:

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

# write here


n s
e h
o o
n w

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
[27]:
emotions = ['Fear', 'Anger','Sadness','Joy','Disgust','Ecstasy']
grade =    [-1,       -1,     -1,       1,     -1,        1]

# write here


Fear : negative
Anger : negative
Sadness : negative
Joy : positive
Disgust : negative
Ecstasy : positive

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
[28]:
s = 'organetto'

# write here


netto
etto
tto
to
o

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
[29]:
s = 'sghiribizzo'
# write here


s
 ghiribizzo
sg
  hiribizzo
sgh
   iribizzo
sghi
    ribizzo
sghir
     ibizzo
sghiri
      bizzo
sghirib
       izzo
sghiribi
        zzo
sghiribiz
         zo
sghiribizz
          o
sghiribizzo

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
[30]:

s1 = "ATACATATAGGGCCAATTATTATAAGTCAC"
s2 = "CGCCACTTAAGCGCCCTGTATTAAAGTCGC"

# write here


ATACATATAGGGCCAATTATTATAAGTCAC
   ||  || |  |  |   |  ||||| |
CGCCACTTAAGCGCCCTGTATTAAAGTCGC

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
[31]:
s =  'sportello'  # sportELLO
#s = 'maglia'     # magLIA

# write here


s
p
o
r
t
E
L
L
O

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
[32]:

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

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

# write here


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!

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
[33]:
#               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


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

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:

[34]:
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?

[35]:
my_list
[35]:
['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
[36]:
la = ['a','b','c']

# write here


['a', 'b', 'c', 'a', 'b', 'c']

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
[37]:

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

# write here


['z', 'a', 'z', 'm', 'z', 'r', 'z']

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
[38]:
sa,sb = 'gibbon', 'ORANGUTAN'   # gOiRbAbNoGnUTAN
#sa,sb = 'cruise ship', 'BOAT'  # cBrOuAiTse ship

# write here


gOiRbAbNoGnUTAN

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.

WARNING: 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
[39]:
# WAY 1

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


# write here


basket: ['melon', 'watermelon', 'melon', 'watermelon']
plate: ['strawberry', 'cherry', 'apple', 'apple']
Show solution
[40]:
# WAY 2

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

# write here


basket: ['melon', 'watermelon', 'melon', 'watermelon']
plate: ['strawberry', 'cherry', 'apple', 'apple']

Iterating a set

Given a set, we can examinate the element sequence with a for cycle.

WARNING: sets iteration order is not predictable !

To better understand why, you can see again the tutorial on sets

[41]:
for word in {'this', 'is', 'a', 'set'}:
    print(word)
this
is
set
a
[42]:
s = set()
s.add('pan')
s.add('de')
s.add('mo')
s.add('nium')
print(s)
{'de', 'mo', 'pan', 'nium'}

Questions - sets

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

  1. s = set()
    s.add('pan')
    s.add('de')
    s.add('mo')
    s.add('nium')
    print(s)
    
  2. for x in {'a',12,'34',56,34}[2:4]:
        print(x)
    
  3. for x in set(['a']) | set(['b']):
        print(x)
    
  4. for x in set(['a']) & set(['b']):
        print(x)
    

Iterating a dictionary

Given a dictionary, we can examinate the sequence of its keys, values or both with a for cycle.

WARNING: keys iteration order is not predictable !

We can go through the keys:

[43]:
pastries = {
    'cream puff':5,
    'brioche':8,
    'donut':2
}
[44]:
for key in pastries:
    print('Found key   :', key)
    print('  with value:', pastries[key])
Found key   : donut
  with value: 2
Found key   : cream puff
  with value: 5
Found key   : brioche
  with value: 8

At each iteration, the declared variable key is assigned to a key taken from the dictionary, in an order we cannot predict.

We can also directly obtain both the key and the associated value with this notation:

[45]:
for key, value in pastries.items():
    print('Found key  :', key)
    print(' with value:', pastries[key])
Found key  : donut
 with value: 2
Found key  : cream puff
 with value: 5
Found key  : brioche
 with value: 8

.items() return a list of key/value couples, and during each iteration a couple is assigned to the variable key and value.

Dictionary iteration - questions

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

WARNING: Remember the order is IMPOSSIBLE to foresee, so the important bit is to guess all the printed stuff

  1. for x in {'a':1,'b':2,'c':3}:
        print(x)
    
  2. for x in {1:'a',2:'b',3:'c'}:
        print(x)
    
  3. diz = {'a':1,'b':2,'c':3}
    for x in diz:
        print(x[diz])
    
  4. diz = {'a':1,'b':2,'c':3}
    for x in diz:
        print(diz[x])
    
  5. diz = {'a':1,'b':2,'c':3}
    for x in diz:
        if x == 'b':
            print(diz[x])
    
  6. for k,v in {1:'a',2:'b',3:'c'}:
        print(k,v)
    
  7. for x in {1:'a',2:'b',3:'c'}.values():
        print(x)
    
  8. for x in {1:'a',2:'b',3:'c'}.keys():
        print(x)
    
  9. for x in {1:'a',2:'b',3:'c'}.items():
        print(x)
    
  10. for x,y in {1:'a',2:'b',3:'c'}.items():
        print(x,y)
    

Questions - Are they equivalent?

Look at the following code fragments: each contains two parts, A and B. For each fragment, try guessing whether part A will print exactly the same result printed by code in part B

  • FIRST think about the answer

  • THEN try executing

Are they equivalent ? postin

diz = {
    'p':'t',
    'o':'i',
    's':'n',
}

print('A:')
for x in diz.keys():
    print(x)

print('\nB:')
for y in diz:
    print(y)

Are they equivalent ? cortel

diz = {
    'c':'t',
    'o':'e',
    'r':'l',
}

print('A:')
for p,q in diz.items():
    print(q)

print('\nB:')
for x in diz.values():
    print(x)

Are they equivalent ? - gel

diz = {
    'g':'l',
    'e':'e',
    'l':'g',
}

print('A:')
for x in diz.values():
    print(x)

print('\nB:')
for z in diz.items():
    print(z[0])

Are they equivalent ? - giri

diz = {
    'p':'g',
    'e':'i',
    'r':'r',
    'i':'i',
}

print('A:')
for p,q in diz.items():
    if p == q:
        print(p)

print('\nB:')
for x in diz:
    if x == diz[x]:
        print(x)

Are they equivalent - Found

First think if they are equivalent, then check with all the proposed values of k.

Be very careful about this exercise !

Getting this means having really understood dictionaries ;-)

k = 'w'
#k = 'h'
#k = 'y'
#k = 'z'

dct = {
    'w':'s',
    'h':'o',
    'y':'?',
}

print('A:')
for x in dct:
    if x == k:
        print('Found', dct[x])

print('\nB:')
if k in dct:
    print('Found', dct[k])
Show answer

Exercise - color of hearts

✪ Write some code which given a dictionary suits, for each suits prints its color.

Example - given:

suits = {
    'hearts':'red',
    'spades':'black',
    'diamonds':'red',
    'clubs':'black'
}

Prints:

WARNING: do not care about the order in which values are printed!

On your computer you might see different results, the important bit is that all rows get printed.

The color of spades is black
The color of diamonds is red
The color of hearts is red
The color of clubs is black
Show solution
[46]:
suits = {
    'hearts':'red',
    'spades':'black',
    'diamonds':'red',
    'clubs':'black'
}

# write here


The color of spades is black
The color of clubs is black
The color of diamonds is red
The color of hearts is red

Exercise - jewels

✪ In the dictionary jewels some keys are equal to the respective values. Write some code which find such keys and prints them all.

Example - given:

jewels = {
    'rubies': 'jade',
    'opals':'topazes',
    'gems':'gems',
    'diamonds': 'gems',
    'rubies':'rubies'
}

prints:

couple of equal elements: gems and gems
couple of equal elements: rubies and rubies
Show solution
[47]:
jewels = {
    'rubies': 'jade',
    'opals':'topazes',
    'gems':'gems',
    'diamonds': 'gems',
    'rubies':'rubies'
}

# write here


couple of equal elements: rubies and rubies
couple of equal elements: gems and gems

Exercise - powers

✪ Given a number n, write some code which creates a NEW dictionary d containing as keys the numbers from 1 a n INCLUDED, by associating keys to their squares.

Example - given:

n = 5

after your code, it must result:

>>> print(d)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Show solution
[48]:
n = 5

# write here


{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Exercise - flowers

✪ Given a list flowers, write some code which creates a NEW dictionary is_cap which associates to each flower True if the flower name is written all uppercase, and False otherwise

  • HINT: to verify whether a string is all uppercase, use .isupper() method

flowers = ['sunflower','GILLYFLOWER', 'tulip', 'PASSION FLOWER', 'ROSE', 'violet']

prints (they are in alphabetical order because we print with pprint):

>>> from pprint import pprint
>>> pprint(is_cap)
{'GILLYFLOWER': True,
 'PASSION FLOWER': True,
 'ROSE': True,
 'sunflower': False,
 'tulip': False,
 'violet': False}
Show solution
[49]:

flowers = ['sunflower','GILLYFLOWER', 'tulip', 'PASSION FLOWER', 'ROSE', 'violet']

# write here


{'GILLYFLOWER': True,
 'PASSION FLOWER': True,
 'ROSE': True,
 'sunflower': False,
 'tulip': False,
 'violet': False}

Exercise - art

✪ An artist painted a series of works with different techiques. In the dictionary prices he writes the price of each technique. The artist intend to promote a series of exhibitions, and in each of them he will present a particular technique. Supposing for each technique he produced q paintings, show how much he will learn in each exhibition (suppose he sells everything).

Example - given:

q = 20

exhibitions = ['watercolor', 'oil', 'mural', 'tempera', 'charcoal','ink']

prices = {'watercolor': 3000,
          'oil'       : 6000,
          'mural'     : 2000,
          'tempera'   : 4000,
          'charcoal'  : 7000,
          'ink'       : 1000
}

Prints - this time order matters!!

Expected Income:
  exhibition watercolor : 60000 €
  exhibition oil : 120000 €
  exhibition mural : 40000 €
  exhibition tempera : 80000 €
  exhibition charcoal : 140000 €
  exhibition ink : 20000 €
Show solution
[50]:
q = 20

exhibitions = ['watercolor', 'oil', 'mural', 'tempera', 'charcoal','ink']

prices = {'watercolor': 3000,
          'oil'       : 6000,
          'mural'     : 2000,
          'tempera'   : 4000,
          'charcoal'  : 7000,
          'ink'       : 1000
}

# write here


Expected Income:
  exhibition watercolor : 60000 €
  exhibition oil : 120000 €
  exhibition mural : 40000 €
  exhibition tempera : 80000 €
  exhibition charcoal : 140000 €
  exhibition ink : 20000 €

Exercise - stationery stores

✪ An owner of two stationery shops, in order to reorganize the stores wants to know the materials which are in common among the shops. Given two dictionaries store1 and store2 which associates objects to their quantity, write some code which finds all the keys in common and for each prints the sum of the found quantities.

Example - given:

store1 = {'pens':10,
          'folders':20,
          'papers':30,
          'scissors':40}

store2 = {'pens':80,
          'folders':90,
          'goniometer':130,
          'scissors':110,
          'rulers':120,
          }

prints (order is not important):

materials in common:
   pens : 90
   folders : 110
   scissors : 150
Show solution
[51]:
store1 = {'pens':10,
          'folders':20,
          'papers':30,
          'scissors':40}

store2 = {'pens':80,
          'folders':90,
          'goniometer':130,
          'scissors':110,
          'rulers':120,
          }
# write here


materials in common:
   pens : 90
   folders : 110
   scissors : 150

Exercise - legumes

✪ A store has numbered shelves, each containing a number of legumes expressed in kilograms. We represent store as a list. There is also a registry available as a dictionary which associates to legume names the shelves number in which they are contained.

Write some code which given a list of legume names, shows the sum of kilograms in the store for those legumes.

Example - given:

legumes = ['lentils', 'soy']

#        0  1  2  3  4  5
store = [50,90,70,10,20,50]

registry = {'peas':3,
            'soy':1,
            'chickpeas':5,
            'lentils':4,
            'broad beans':2,
            'beans':0,
}

after your code, it must print (order does not matter):

Searching for lentils and soy ...
Found 20 kg of lentils
Found 90 kg of soy
Total: 110 kg
Show solution
[52]:

legumes = ['lentils', 'soy']    # 110
#legumes = ['beans', 'broad beans', 'chickpeas']   # 170

#        0  1  2  3  4  5
store = [50,90,70,10,20,50]

registry = {'peas':3,
            'soy':1,
            'chickpeas':5,
            'lentils':4,
            'broad beans':2,
            'beans':0,
}
# write here


Searching for lentils and soy ...
Found 20 kg of lentils
Found 90 kg of soy
Total: 110 kg

Exercise - sports

✪✪ Write some code which given a dictionary sports in which people are associated to the favourite sport, create a NEW dictionari counts in which associates each sport to the number of people that prefer it

Exemple - given:

sports = {
    'Gianni':'soccer',
    'Paolo':'tennis',
    'Sara':'volleyball',
    'Elena':'tennis',
    'Roberto':'soccer',
    'Carla':'soccer',
}

After your code, it must result:

>>> print(counts)
{'tennis': 2, 'soccer': 3, 'volleyball': 1}
Show solution
[53]:
sports = {
    'Gianni':'soccer',
    'Paolo':'tennis',
    'Sara':'volleyball',
    'Elena':'tennis',
    'Roberto':'soccer',
    'Carla':'soccer',
}

# write here


{'tennis': 2, 'volleyball': 1, 'soccer': 3}

Modifying a dictionary during iteration

Suppose you have a dictionary of provinces:

provinces = {
    'tn': 'Trento',
    'mi':'Milano',
    'na':'Napoli',
}

and you want to MODIFY it so that after your code the acronyms are added as capitalized:

>>> print(provinces)
{'tn': 'Trento',
 'mi':'Milano',
 'na':'Napoli',
 'TN': 'Trento',
 'MI':'Milano',
 'NA':'Napoli',
}

You might think to write something like this:

for key in provinces:
    provinces[key.upper()] = provinces[key]    # WARNING !

QUESTION: Do you see any problem?

Show answer

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

In this case, if we try executing the code, we will get an explicit error:

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-26-9b20900057e8> in <module>()
----> 1 for key in provinces:
      2     provinces['chiave'.upper()] = provinces[key]    # WARNING !

RuntimeError: dictionary changed size during iteration

but in other cases (like for example lists) modifying stuff may produce totally unpredictable behaviours (do you know the expression pulling the rug out from under your feet ? )

What about removing? We’ve seen adding is dangerous, but so is removing.

Suppose we want to remove any couple having as value 'Trento'

provinces = {
    'tn': 'Trento',
    'mi':'Milano',
    'na':'Napoli',
}

to obtain:

>>> print(provinces)
{'mi':'Milano',
 'na':'Napoli'}

If we try executing something like this Python notices and raises an exception:

provinces = {
    'tn': 'Trento',
    'mi':'Milano',
    'na':'Napoli',
}

for key in provinces:
    if provinces[key] == 'Trento':
        del provinces[key]   # VERY BAD IDEA
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-23-5df0fd659120> in <module>()
      5     'na':'Napoli'
      6 }
----> 7 for key in provinces:
      8     if provinces[key] == 'Trento':
      9         del provinces[key]   # VERY BAD IDEA

RuntimeError: dictionary changed size during iteration

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

Exercise - zazb

✪✪ Write some code which given a dictionary chars with characters as keys, MODIFY the dictionary so to add keys like the existing ones prefixed with character 'z' - new keys should be associated with the constant integer 10

Example - given:

chars = {
    'a':3,
    'b':8,
    'c':4
}

after your code, chars should result MODIFIED like this:

>>> chars
{   'a':3,
    'b':8,
    'c':4,
    'za':10,
    'zb':10,
    'zc':10
}

QUESTION: Is it desirable to write a solution like the following one? Read carefully!

chars = {
    'a':3,
    'b':8,
    'c':4
}

for key in chars:
    chars['z'+key] = 10    # WARNING !! TROUBLE AHEAD !!
Show answerShow solution
[54]:

chars = {
    'a':3,
    'b':8,
    'c':4
}

# write here


Nested for

Pay attention when using names of variables in nested for loops:

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

If you defined a variable in an external for, you shall not reintroduce it in an internal for, because this would bring a lot of confusion. For example here s is introduced both in the external and in the internal loop:

[55]:
for s in ['volleyball', 'tennis', 'soccer', 'swimming']:

    for s in range(3):  # debugging hell, you lose the external cycle s
        print(s)

    print(s)  # prints 2 instead of a sport!
0
1
2
2
0
1
2
2
0
1
2
2
0
1
2
2

Questions - nested for

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

  1. for y in for x in range(3):
        print(x,y)
    
  2. for y in for x in range(2) in range(3):
        print(x,y)
    
  3. for y in range(3):
        for x in range(2):
            print(x,y)
    
  4. for x in range(2):
        for x in range(3):
            print(x)
        print(x)
    
  5. for x in range(2):
        for y in range(3):
            print(x,y)
        print(x,y)
    
  6. for x in range(1):
        for y in range(1):
            print(x,y)
    
  7. for x in range(2):
        for y in range(3):
            print(x,y)
    
  8. la = 'abc'
    for x in la:
        for y in la:
            print(x)
    
  9. for x in 'ab':
        for y in 'cd':
            print(x,y)
        for y in 'ef':
            print(x,y)
    
  10. for x in 'abc':
        for y in 'abc':
            if x == y:
                print(x)
    
  11. for x in 'abc':
        for y in 'abc':
            if x != y:
                print(x,y)
    
  12. lista = []
    for x in 'a':
        for y in 'bc':
            lista.append(x)
            lista.append(y)
    print(lista)
    
  13. lista = []
    for x in 'abc':
        for y in 'de':
            lista.append('z')
    print(len(lista))
    
  14. c = 1
    for x in range(1,4):
        s = ''
        for y in range(1,4):
            s = s + str(c)
            c += 1
        print(s)
    

Exercise - casting

✪ A new USA-Japanese videocultural production is going to be launched, so actors are called for casting. The director wants to try a scene with all the possible couples which can be formed among actors and actresses. Write some code which prints all the couples, also putting introduction messages.

  • NOTE: the number of actors and actresses may be different

Exemple - given:

actresses = ['Leela','Wilma']
actors = ['Capitan Harlock', 'Lupin', 'Kenshiro']

prints:

Leela enters the scene!
   Capitan Harlock enters the scene!
      Leela and Capitan Harlock get ready ... ACTION!
    Thanks Capitan Harlock - next one !
   Lupin enters the scene!
      Leela and Lupin get ready ... ACTION!
    Thanks Lupin - next one !
   Kenshiro enters the scene!
      Leela and Kenshiro get ready ... ACTION!
    Thanks Kenshiro - next one !
Thanks Leela - next one !
Wilma enters the scene!
   Capitan Harlock enters the scene!
      Wilma and Capitan Harlock get ready ... ACTION!
    Thanks Capitan Harlock - next one !
   Lupin enters the scene!
      Wilma and Lupin get ready ... ACTION!
    Thanks Lupin - next one !
   Kenshiro enters the scene!
      Wilma and Kenshiro get ready ... ACTION!
    Thanks Kenshiro - next one !
Thanks Wilma - next one !

Casting is over for today!
Show solution
[56]:
actresses = ['Leela','Wilma']
actors = ['Capitan Harlock', 'Lupin', 'Kenshiro']


# write here


Leela enters the scene!
   Capitan Harlock enters the scene!
      Leela and Capitan Harlock get ready ... ACTION!
    Thanks Capitan Harlock - next one !
   Lupin enters the scene!
      Leela and Lupin get ready ... ACTION!
    Thanks Lupin - next one !
   Kenshiro enters the scene!
      Leela and Kenshiro get ready ... ACTION!
    Thanks Kenshiro - next one !
Thanks Leela - next one !
Wilma enters the scene!
   Capitan Harlock enters the scene!
      Wilma and Capitan Harlock get ready ... ACTION!
    Thanks Capitan Harlock - next one !
   Lupin enters the scene!
      Wilma and Lupin get ready ... ACTION!
    Thanks Lupin - next one !
   Kenshiro enters the scene!
      Wilma and Kenshiro get ready ... ACTION!
    Thanks Kenshiro - next one !
Thanks Wilma - next one !

Casting is over for today!

Exercise - cover the plane

✪ Given the integers a and b, write some code which prints all the possible couples of numbers \(x\) and \(y\) such that \(1 \leq x \leq a\) and \(1 \leq y \leq b\)

For example, given:

a,b = 5,3

it must print:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
4 1
4 2
4 3
5 1
5 2
5 3
Show solution
[57]:
a,b = 5,3

# write here


1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
4 1
4 2
4 3
5 1
5 2
5 3

Exercise - triangular

✪ Given the integer a, write some code which prints all the possible couples of numbers \(x\) and \(y\) such that \(0 \leq x \leq y < a\)

For example, for

a = 5

it must print:

0 0
0 1
0 2
0 3
0 4
1 1
1 2
1 3
1 4
2 2
2 3
2 4
3 3
3 4
4 4
Show solution
[58]:
a = 5
# write here


0 0
0 1
0 2
0 3
0 4
1 1
1 2
1 3
1 4
2 2
2 3
2 4
3 3
3 4
4 4

Exercise - port

✪ Write some code which given a list words and a list characters, for each word calculates how many characters it contains

  • ONLY count the characters present in characters

  • ONLY print the result if the number is greater than zero

Example - given:

words = ['ships','pier','oar','fish trap','sails','trawling net']
characters = ['n','i','s']

prints:

ships contains 1 i
ships contains 2 s
pier contains 1 i
fish trap contains 1 i
fish trap contains 1 s
sails contains 1 i
sails contains 2 s
trawling net contains 2 n
trawling net contains 1 i
Show solution
[59]:
words = ['ships','pier','oar','fish trap','sails','trawling net']
characters = ['n','i','s']


# write here


ships contains 1 i
ships contains 2 s
pier contains 1 i
fish trap contains 1 i
fish trap contains 1 s
sails contains 1 i
sails contains 2 s
trawling net contains 2 n
trawling net contains 1 i

Exercise - polygons

✪✪ Given a list polygons with polygon names ordered by sides number starting from a triangle, write some code which prints all the possible questions we can form regarding the number of sides. Start from a minimum of 3 sides until a maximum corresponding to the number of sides of the last polygon (remember names are ordered by number of sides!)

Example - given:

#               0          1        2           3
polygons = ["triangle","square","pentagon", "hexagon"]

prints:

Does the triangle have 3 sides? True
Does the triangle have 4 sides? False
Does the triangle have 5 sides? False
Does the triangle have 6 sides? False
Does the square have 3 sides? False
Does the square have 4 sides? True
Does the square have 5 sides? False
Does the square have 6 sides? False
Does the pentagon have 3 sides? False
Does the pentagon have 4 sides? False
Does the pentagon have 5 sides? True
Does the pentagon have 6 sides? False
Does the hexagon have 3 sides? False
Does the hexagon have 4 sides? False
Does the hexagon have 5 sides? False
Does the hexagon have 6 sides? True
Show solution
[60]:
#                 0              1              2             3
polygons = ["triangle","square","pentagon", "hexagon"]

# write here


Does the triangle have 3 sides? True
Does the triangle have 4 sides? False
Does the triangle have 5 sides? False
Does the triangle have 6 sides? False
Does the square have 3 sides? False
Does the square have 4 sides? True
Does the square have 5 sides? False
Does the square have 6 sides? False
Does the pentagon have 3 sides? False
Does the pentagon have 4 sides? False
Does the pentagon have 5 sides? True
Does the pentagon have 6 sides? False
Does the hexagon have 3 sides? False
Does the hexagon have 4 sides? False
Does the hexagon have 5 sides? False
Does the hexagon have 6 sides? True

Exercise - bon jour

✪✪✪ Given two strings sa and sb in lowercase, write some code which prints single letters from sa as upper case, followed by all possible combinations of sb where ONLY ONE character is uppercase.

Example - given:

sa = 'bon'
sb = 'jour'

Must print:

B Jour
B jOur
B joUr
B jouR
O Jour
O jOur
O joUr
O jouR
N Jour
N jOur
N joUr
N jouR
Show solution
[61]:
sa = 'bon'
sb = 'jour'

# write here


B Jour
B jOur
B joUr
B jouR
O Jour
O jOur
O joUr
O jouR
N Jour
N jOur
N joUr
N jouR

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:

[62]:
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.

[63]:
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:

[64]:
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 !
[64]:

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
[65]:
phrase = 'autonomous walking'
#phrase='continuous'

# write here


t
n
m
s

w
l
k
n
g

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
[66]:
string = 'cascapirillabadgnippobadzarpogno'  # cascapirilla
#string = 'sobad'  # 'so'
#string = 'bad'  # ''
#string = 'badso'  # ''

for i in range(len(string)):
    if string[i:i+3] == 'bad':
        break
    else:
        print(string[i])
c
a
s
c
a
p
i
r
i
l
l
a

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
[67]:
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


At
some
point
you
must
stop

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
[68]:
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!
[ ]: