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"]

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


In [ ]:

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}

Next, write a loop that sums up the prices.


In [ ]:

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

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

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

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


In [ ]:

Then, create a new list consisting of sums of the (x,y) pairs.


In [ ]:

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


In [ ]:

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 [2]:
numbers = range(1, 101)

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

value = random.random()
value


Out[5]:
0.3504138821505054

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 [ ]:
temperatures_celsius = [0, -15, 20.15, 13.3, -5.2]