For loops 7 - nested loops

Browse file online

It’s possible to include a for cycle inside another one, for example we could visit all the words of a list of strings and for each word we could print all its characters:

[2]:

lst = ["some",
"light",

for string in lst:
for char in string:
print(char)
print()

s
o
m
e

l
i
g
h
t

a
h
e
a
d



Nested for

What we said previously about variable names is even more important with nested 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:

[3]:

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. lst = []
for x in 'a':
for y in 'bc':
lst.append(x)
lst.append(y)
print(lst)

13. lst = []
for x in 'abc':
for y in 'de':
lst.append('z')
print(len(lst))

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

Example - given:

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


prints:

Leela enters the scene!
Captain Harlock enters the scene!
Leela and Captain Harlock get ready ... ACTION!
Thanks Captain 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!
Captain Harlock enters the scene!
Wilma and Captain Harlock get ready ... ACTION!
Thanks Captain 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
[4]:

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

# write here


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

a,b = 5,3

# write here


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

a = 5
# write here


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

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

# write here


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

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

# write here


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

sa = 'bon'
sb = 'jour'

# write here


Continue

Go on with for challenges

[ ]: