Control Structures

Simple for loop

Write a for loop which iterates over the list of breakfast items "sausage", "eggs", "bacon" and "spam" and prints out the name of item


In [ ]:
breakfast = ["sausage", "eggs", "bacon", "spam"]
for item in breakfast:
    print(item)

Write then a for which loop determines the squares of the odd integers up to 10. Use the range() function.


In [ ]:
squares = []
for i in range(1, 10, 2):
    squares.append(i**2)
print(squares)

Looping through a dictionary

Write a loop that prints out the names of the fruits in the dictionary containing the fruit prices.


In [ ]:
fruits = {'banana' : 5, 'strawberry' : 7, 'pineapple' : 3}
for fruit in fruits:
    print(fruit)

Next, write a loop that sums up the prices.


In [ ]:
sum = 0
for price in fruits.values():
    sum += price
print(sum)

While loop

Fibonacci numbers are a sequence of integers defined by the recurrence relation

        F[n] = F[n-1] + F[n-2]

with the initial values F[0]=0, F[1]=1. Create a list of Fibonacci numbers F[n] < 100 using a while loop.


In [ ]:
f = [0, 1]
while True:
    new = f[-1] + f[-2]
    if new > 100:
        break
    f.append(new)
print(f)

If - else

Write a control structure which checks whether an integer is negative, zero, or belongs to the prime numbers 3,5,7,11,17 and perform e.g. corresponding print statement.

Use keyword in when checking for belonging to prime numbers.


In [ ]:
number = 7
if number < 0:
    print("Negative")
elif number == 0:
    print("Zero")
elif number in [3, 5, 7, 11, 17]:
    print("Prime")

Advanced exercises

Don't worry if you don't have time to finish all of these. They are not essential.

Looping through multidimensional lists

Start from a two dimensional list of (x,y) value pairs, and sort it according to y values. (Hint: you may need to create a temporary list).


In [ ]:
xys =  [[2, 3], [0, -1], [4, -2], [1, 6]]
tmp = []
for x, y in xys:
    tmp.append([y,x])
tmp.sort()
for i, (y,x) in enumerate(tmp):
    xys[i] = [x,y]
print(xys)

Next, create a new list containing only the sorted y values.


In [ ]:
ys = []
for x, y in xys:
    ys.append(y)
print(ys)

Finally, create a new list consisting of sums the (x,y) pairs where both x and y are positive.


In [ ]:
sums = []
for x, y in xys:
    if x > 0 and y > 0:
        sums.append(x + y)
print(sums)

List comprehension is often convenient in this kind of situations:


In [ ]:
xys = [[2, 3], [0, -1], [4, -2], [1, 6]]
tmp = [[y, x] for x, y in xys]
tmp.sort()
xys = [[x, y] for y, x in tmp]

# One liner is possible but not very readable anymore:
xys = [[x, y] for y, x in sorted([[ytmp, xtmp] for xtmp, ytmp in xys])]

# Summing positives with one liner is ok:
sums = [x+y for x,y in xys if x > 0 and y > 0]

FizzBuzz

This is a classic job interview question. Depending on the interviewer or interviewee it can filter out up to 95% of the interviewees for a position. The task is not difficult but it's easy to make simple mistakes.

If a number is divisible by 3, instead of the number print "Fizz", if a number is divisible by 5, print "Buzz" and if the number is divisible by both 3 and 5, print "FizzBuzz".


In [8]:
for number in range(1, 101):
    if number % 3 == 0 and number % 5 == 0:
        print("FizzBuzz")
    elif number % 3 == 0:
        print("Fizz")
    elif number % 5 == 0:
        print("Buzz")
    print(number)


1
2
Fizz
3
4
Buzz
5
Fizz
6
7
8
Fizz
9
Buzz
10
11
Fizz
12
13
14
FizzBuzz
15
16
17
Fizz
18
19
Buzz
20
Fizz
21
22
23
Fizz
24
Buzz
25
26
Fizz
27
28
29
FizzBuzz
30
31
32
Fizz
33
34
Buzz
35
Fizz
36
37
38
Fizz
39
Buzz
40
41
Fizz
42
43
44
FizzBuzz
45
46
47
Fizz
48
49
Buzz
50
Fizz
51
52
53
Fizz
54
Buzz
55
56
Fizz
57
58
59
FizzBuzz
60
61
62
Fizz
63
64
Buzz
65
Fizz
66
67
68
Fizz
69
Buzz
70
71
Fizz
72
73
74
FizzBuzz
75
76
77
Fizz
78
79
Buzz
80
Fizz
81
82
83
Fizz
84
Buzz
85
86
Fizz
87
88
89
FizzBuzz
90
91
92
Fizz
93
94
Buzz
95
Fizz
96
97
98
Fizz
99
Buzz
100

Food for thought: How do people commonly fail this test and why?


In [ ]:

Breaking

The python random module generates pseudorandom numbers.

Write a while loop that runs until the output of random.random() is below 0.1 and break when the value is below 0.1.


In [10]:
import random

while True:
    value = random.random() 
    if value < 0.1:
        break
print("done")


done

List comprehension

Using a list comprehension create a new list, temperatures_kelvin from following Celsius temperatures and convert them by adding the value 273.15 to each.


In [12]:
temperatures_celsius = [0, -15, 20.15, 13.3, -5.2]

temperatures_kelvin = [c+273.15 for c in temperatures_celsius]