Exercises

Chapter 1

Numbers

Fahrenheit to Celsius

  1. Create a variable fahrenheit which stores the current temperature in Zurich in Fahrenheit (Google: “zurich temperature fahrenheit”).

  2. The formula to convert Fahrenheit to Celsius is: \(C = (5/9)(F-32)\). Create a new variable celsius which converts Fahrenheit to Celsius using this formula.

  3. Print out the variable using the print function.

fahrenheit = 82 
celsius = (5/9) * (fahrenheit - 32)
print("The temperature in Celsius is:", celsius)
The temperature in Celsius is: 27.77777777777778

Strings

String theory

Consider the (slightly altered) transcript of an xkcd comic:

String Theory summarized: I just had an awesome idea. Suppose all matter and energy is made of tiny, vibrating "strings". Okay ... what would that imply? I dunno.

  1. Store this transcript as a string in the variable xkcd. Print it out using the print function.

  2. How long is the string in total?

  3. Extract the first character of the second word.

  4. Extract the first word, the second word and the last word separately using slicing and store them in the variables xkcd_1, xkcd_2 and xkcd_last. Print out xkcd_1 and xkcd_2 together.

  5. How would the string read backwards?

  6. Count how often the word ‘I’ is used in this string.

  7. Split the string at every dot and store the resulting list in the variable xkcd_list. Print this list out.

  8. Join the strings in the list xkcd_list using the dot as a separator argument and assign them to a variable xkcd_rejoined. Print the variable out.

  9. Replace the word ‘strings’ with the word ‘ducks’ in xkcd and store the result in the variable duck_theory. Replace the word ‘String’ with the word ‘Duck’ in duck_theory and store the result again in the variable duck_theory. Print it out.

1)

xkcd = ('String Theory summarized: I just had an awesome idea. Suppose all matter and energy is made of tiny, '
       'vibrating "strings". Okay ... what would that imply? I dunno.')

2)

len(xkcd)
162

3)

xkcd[7]
'T'

4)

xkcd_1 = xkcd[:6] 
print(xkcd_1)
String
xkcd_2 = xkcd[7:14]
print(xkcd_2)
Theory 
xkcd_last = xkcd[-6:-1]
print(xkcd_last)
dunno
print(xkcd_1, xkcd_2) 
String Theory 
xkcd_combined = xkcd_1 + ' ' + xkcd_2 
print(xkcd_combined)
String Theory 

5)

print(xkcd[::-1])
.onnud I ?ylpmi taht dluow tahw ... yakO ."sgnirts" gnitarbiv ,ynit fo edam si ygrene dna rettam lla esoppuS .aedi emosewa na dah tsuj I :dezirammus yroehT gnirtS

6)

xkcd.count('I')
2

7)

xkcd.split('.')
['String Theory summarized: I just had an awesome idea',
 ' Suppose all matter and energy is made of tiny, vibrating "strings"',
 ' Okay ',
 '',
 '',
 ' what would that imply? I dunno',
 '']
xkcd_list = xkcd.split('.')
xkcd_rejoined = '.'.join(xkcd_list)
print(xkcd_rejoined)
String Theory summarized: I just had an awesome idea. Suppose all matter and energy is made of tiny, vibrating "strings". Okay ... what would that imply? I dunno.

9)

duck_theory = xkcd.replace('strings', 'ducks')
duck_theory = duck_theory.replace('String', 'Duck')
print(duck_theory)
Duck Theory summarized: I just had an awesome idea. Suppose all matter and energy is made of tiny, vibrating "ducks". Okay ... what would that imply? I dunno.

Chapter 2

Lists

Operating Systems

  1. Create a list of the ‘founding fathers’ of today’s existing operating systems / companies: Linus Torvalds, Bill Gates, and Steve Jobs. Call it founders. Print it out.

  2. You realize that Steve Jobs shouldn’t be on that list. Instead you want Steve Wozniak on the list. Change the list by removing Steve Jobs and adding Steve Wozniak. Print it out.

  3. Sort the list alphabetically.

  4. Create another list, os_list, with the names of the operating systems: OS X, Windows, and Linux.

  5. Combine the two lists in a new list called modern_pc.

  6. How would you test whether FreeBSD is in modern_pc?

1)

founders = ['Linus Torvalds', 'Bill Gates', 'Steve Jobs']
print(founders)
['Linus Torvalds', 'Bill Gates', 'Steve Jobs']

2)

founders[2] = 'Steve Wozniak'
print(founders)
['Linus Torvalds', 'Bill Gates', 'Steve Wozniak']

3)

founders.sort()
print(founders)
['Bill Gates', 'Linus Torvalds', 'Steve Wozniak']
help(list.sort)
Help on method_descriptor:

sort(self, /, *, key=None, reverse=False)
    Sort the list in ascending order and return None.
    
    The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
    order of two equal elements is maintained).
    
    If a key function is given, apply it once to each list item and sort them,
    ascending or descending, according to their function values.
    
    The reverse flag can be set to sort in descending order.

4)

os_list = ['OS X', 'Windows', 'Linux']

5)

modern_pc = founders + os_list
print(modern_pc)
['Bill Gates', 'Linus Torvalds', 'Steve Wozniak', 'OS X', 'Windows', 'Linux']

6)

'FreeBSD' in modern_pc
False

Tuples

Boring but necessary

  1. Create a tuple which contains the name of your favorite band. Call it my_favorite_band. Check whether it is a tuple.

  2. Create a tuple called record which contains your name, your address and your email contact as elements. Use tuple unpacking to assign the three elements in this tuple to the variables name, address and email.

1)

# you need the trailing comma
my_favorite_band = 'The National',

2)

record = ('Julian Langer', 'Langstrasse 81', 'julian.langer@econ.uzh.ch')

3)

# tuple unpacking
name, address, email = record
print(name)
Julian Langer

Dictionaries

Explain a Film Plot Badly

The descriptions are:

  • Teenager recruited to a terrorist organization destroys govt facility killing thousands.

  • Professor has unusually productive sabbatical.

  • Paranoid billionaire afraid of immigrant.

  • Rare endangered aquatic creature murdered by small town blue collar sheriff.

The movies are:

  • Batman v Superman

  • Jaws

  • Indiana Jones

  • Star Wars

  1. Order movies and descriptions correctly and put them in a dictionary called movie_descriptions, where movie titles are used as keys.

  2. Print out the description for Jaws.

  3. We think there is a better description for Star Wars. Change it to the following: Deadbeat dad tries to get his son to take over the family business.

  4. Print out all movie titles and descriptions separately.

  5. Store all items from movie_descriptions in a list called bad_descriptions.

1)

movie_descriptions = { 'Batman v Superman' : 'Paranoid billionaire afraid of immigrant.',
                     'Jaws' : 'Rare endangered aquatic creature murdered by small town blue collar sheriff.',
                     'Indiana Jones' : 'Professor has unusually productive sabbatical.',
                     'Star Wars' : 'Teenager recruited to a terrorist organization destroys govt facility killing thousands.'}

2)

print(movie_descriptions['Jaws'])
Rare endangered aquatic creature murdered by small town blue collar sheriff.

3)

movie_descriptions['Star Wars'] = 'Deadbeat dad tries to get his son to take over the family business.'
print(movie_descriptions)
{'Batman v Superman': 'Paranoid billionaire afraid of immigrant.', 'Jaws': 'Rare endangered aquatic creature murdered by small town blue collar sheriff.', 'Indiana Jones': 'Professor has unusually productive sabbatical.', 'Star Wars': 'Deadbeat dad tries to get his son to take over the family business.'}

4)

print(movie_descriptions.keys())
dict_keys(['Batman v Superman', 'Jaws', 'Indiana Jones', 'Star Wars'])
print(movie_descriptions.values())
dict_values(['Paranoid billionaire afraid of immigrant.', 'Rare endangered aquatic creature murdered by small town blue collar sheriff.', 'Professor has unusually productive sabbatical.', 'Deadbeat dad tries to get his son to take over the family business.'])

5)

bad_descriptions = list(movie_descriptions.items())
print(bad_descriptions)
[('Batman v Superman', 'Paranoid billionaire afraid of immigrant.'), ('Jaws', 'Rare endangered aquatic creature murdered by small town blue collar sheriff.'), ('Indiana Jones', 'Professor has unusually productive sabbatical.'), ('Star Wars', 'Deadbeat dad tries to get his son to take over the family business.')]

As you can see, if you convert the items of the dictionary into a list, it becomes a list of 2-element tuples. Note that you need the items method here, otherwise the list would just contain the keys.

Chapter 3

Guess a number (from Lubovic)

  1. Create a variable my_number with your favorite number between 1 and 10.

  2. Create a second variable guess for which you can choose an arbitrary number between 1 and 10.

  3. Write an if-else structure which prints out Too low. if the guess is lower than your favorite number, Too high if the guess is higher than your favorite number and Just right. if it is exactly equal to your favorite number.

my_number = 7
guess = 5

if guess < my_number: 
    print('Too low.')
elif guess > my_number: 
    print('Too high.')
else: 
    print('Just right!')
Too low.

Guess a number 2.0 (from Lubovic)

  1. Create a variable my_number with your favorite number between 1 and 20.

  2. Write a while loop which prompts the reader to input a number between 1 and 20 and store it as my_guess. At each iteration the while loop should evaluate whether the guess is still False. Moreover, if the number is too low, Python should print this out and similarly for the case where the number is too high. When the correct number is entered, Python should print out Found it! and exit the loop.

my_number = 17
guess = False


while guess == False:
    my_guess = int(input('Please enter a number between 1 and 20:'))
    
    if my_guess < 1 or my_guess > 20:
        print('Out of range.')
        continue
    
    if my_guess > my_number: 
        print('Guess is too high!')
    elif my_guess < my_number: 
        print('Guess is too low!')
    else:
        print('Found it!')
        guess = True
---------------------------------------------------------------------------
StdinNotImplementedError                  Traceback (most recent call last)
/tmp/ipykernel_2384/1184762823.py in <module>
      4 
      5 while guess == False:
----> 6     my_guess = int(input('Please enter a number between 1 and 20:'))
      7 
      8     if my_guess < 1 or my_guess > 20:

/opt/hostedtoolcache/Python/3.8.11/x64/lib/python3.8/site-packages/ipykernel/kernelbase.py in raw_input(self, prompt)
   1001         """
   1002         if not self._allow_stdin:
-> 1003             raise StdinNotImplementedError(
   1004                 "raw_input was called, but this frontend does not support input requests."
   1005             )

StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.

while vs. for

  1. Write down your favorite line from a song and store it in a string called my_line.

  2. Split the string into single words and store the results in a list called lyrics_list.

  3. Write a while loop and a for loop which iterate through the list and reconstruct the original string.

  4. After the end of the loop, the line should be printed out again.

my_line = "We don't need no education."
lyrics_list = my_line.split(' ')
print(lyrics_list)
['We', "don't", 'need', 'no', 'education.']
current = 0
lyrics = ''
while current < len(lyrics_list): 
    lyrics = lyrics + ' ' + lyrics_list[current]
    current += 1
    print(lyrics)
 We
 We don't
 We don't need
 We don't need no
 We don't need no education.
lyrics = ''
for word in lyrics_list:
    lyrics = lyrics + ' ' + word
    print(lyrics)
 We
 We don't
 We don't need
 We don't need no
 We don't need no education.

zip and dictionaries (from Lubovic)

  1. Use zip to make a dictionary called movies that pairs these lists: titles = ['Creature of Habit', 'Crewel Fate'] and plots = ['A nun turns into a monster', 'A haunted yarn shop'].

titles = ['Creature of Habit', 'Crewel Fate']
plots = ['A nun turns into a monster', 'A haunted yarn shop']
movies = {}

for title, plot in zip(titles, plots): 
    movies[title] = plot

print(movies)
{'Creature of Habit': 'A nun turns into a monster', 'Crewel Fate': 'A haunted yarn shop'}

Sequences

  1. Use a for-loop to print the values from +5 to -5.

for number in range(5, -6, -1):
    print(number)
5
4
3
2
1
0
-1
-2
-3
-4
-5

Comprehensions

number_list = list(range(1, 21))
my_list = [number**2 for number in number_list if number % 3 != 0]
print(my_list)
[1, 4, 16, 25, 49, 64, 100, 121, 169, 196, 256, 289, 361, 400]

Chapter 4

Defining and running functions

Assume the following constant elasticity of substitution (CES) utility function: \(U(x, y) = \frac{x^\delta}{\delta} + \frac{y^\delta}{\delta}\) with \(\delta < 1\) and \(\delta \neq 0\).

  1. Define the function ces_utility and call it with \(x = 1, y = 2, \delta = -1\).

  2. Call the function using positional and keyword arguments.

  3. Define a default parameter for \(\delta = 0.5\) and call the function with it.

  4. Document the function. What does it do? What are its inputs and outputs.

def ces_utility(x, y, delta): 
    u = (x**delta)/delta + (y**delta)/delta
    return u
ces_utility(1, 2, -1) 
-1.5
print(ces_utility(1, 2, -1))
print(ces_utility(y = 2, x = 1, delta = -1))
-1.5
-1.5
def ces_utility(x, y, delta = 0.5): 
    u = (x**delta)/delta + (y**delta)/delta
    return u
ces_utility(x = 1, y = 2)
4.82842712474619
def ces_utility(x, y, delta = 0.5): 
    '''Calculates the CES utility. 
    Inputs: 
    * x: good 1 (numeric) 
    * y: good 2 (numeric) 
    * delta: governs elasticity of substitution (numeric)
    
    Output: utility (numeric) '''
    u = (x**delta)/delta + (y**delta)/delta
    return u

Functions as objects

  1. Write a function nl_apply which takes a list of numbers and function as arguments, and applies the function to each element of the list.

  2. Write a function plus_one, which takes a number as an input and increases it by 1.

  3. Call the function nl_apply with a list of numbers from 1 to 10 and the function plus_one as arguments. Store the result in the variable result and print it out.

def nl_apply(list_of_numbers, func): 
    result = []
    for number in list_of_numbers:
        result.append(func(number))
    return result

def plus_one(number): 
    return number + 1

nl_apply(range(1, 11), plus_one)
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

Error handling with try and except

  1. Write a function add_stuff which adds two numbers given to it as arguments.

  2. Call it without arguments. Observe what happens.

  3. Use a try-except structure to explain the error. Call the function without arguments again.

def add_stuff(x, y): 
    return x + y

try:
    add_stuff()
    
except TypeError:
    print('You forgot to pass two numbers to the function!')
You forgot to pass two numbers to the function!

Modules

  1. Create a file called hitchhiker.py in your current working directory.

  2. Open it and define a function called meaning_of_life. The function should print out: The meaning of life is 42!

  3. Open a new notebook or script. Import the module hitchhiker and run the function.

  4. Import the module as adams and call the function.

  5. Import just the function meaning_of_life and call it.

  6. Import the function as deep_thought and call it.

No solution provided here.