Solutions to the preparatory exercises

Here are the solutions to the exercises that help you to decide whether you should watch the introductory video lectures and/or read the respective scripts.

These lectures are addressed to beginners who have no previous programming experience at all, so depending on your knowledge you can also watch them selectively.

In case you have questions or problems please do not hesitate to contact Claudius via mail.

1. Basics

1.1 What is an operator?

Operators are symbols that tell Python to carry our a particular form of computation. The operator +, for example, tells python to add the objects before and after the operator.

1.2 Which operators help to do the following calculation in Python:

  • Substraction
  • Division
  • Taking roots
In [ ]:
5 - 2 # Substraction
10/2 # Division
2**0.5 # Taking roots

1.3 Bind the result from the calculation $4^2 + 20$ to the identifier x and print it.

In [1]:
x = 4**2 + 20
print(x)
36

1.4 What is a keyword and how does it relate to the concept of an identifier?

An identifier is the name of an object to which something is associated using the = command. In the following code, x and y are identifiers:

In [ ]:
x = 2
y = 4

A keyword is a symbol or string that performs a very particular and important role in Python, and must not be overwritten. There are currently 33 keywords in Python. You can print them using the following code:

In [ ]:
import keyword
keyword.kwlist

2. Data types

2.1 How can you get the type of an object?

The easiest way is using the type function:

In [2]:
type(2.0)
Out[2]:
float

2.2 What type is x in the following code? How can you transform it into a character?

In [3]:
x = 2.0
In [4]:
type(x)
Out[4]:
float
In [5]:
x = int(x)
type(x)
Out[5]:
int

2.3 Explain the difference between integers, floats and strings.

Integers are numbers without a decimal part, floats are numbers with decimal places. As for integers, all conventional mathematical operations are defined for floats. There are mathematical and logical reaons for distinguishing between integers and floats. As in mathematics, integers are required whenever you want to count stuff, or when you want to tell Python to do something x times, or if you want to use them as indices.

Strings are most akin to what we term 'words', and they usually behave very differenty than interers and floats when used with the same operators:

In [6]:
2 + 2
Out[6]:
4
In [7]:
"2" + "2"
Out[7]:
'22'
In [8]:
4*3
Out[8]:
12
In [9]:
4*"3"
Out[9]:
'3333'

2.4 How does the operator + interact with integers, characters and Boolean values?

It implements the mathematical operation 'addition' when used with integers, it concatenates strings, and it adds up Boolean values interpreting True as 1 and False as 0.

2.5 Create a list l1 containing the elemens 4, y and 25. Then substitue the second value with 50 and print the resulting list.

In [10]:
l = [4, "y", 25]
l[1] = 50
print(l)
[4, 50, 25]

2.6 What is the difference between lists, tuples and sets?

All three are collections of elements. By contrast to lists and sets, tuples are immutable.

Sets can be distinguished from tuples and lists by the following properties:

  1. They cannot contain duplicate elements
  2. They can contain elements of different data types
  3. The ordering of their members is not fixed
  4. Sets are mutable (just as lists), but indexing does not work

2.7 Create a list with the numbers from 1 to 10 and save it. Then extract the last three elements and print them.

In [11]:
l2 = list(range(1, 11))
l2
Out[11]:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

2.8 Sort the list in decreasing order and print it.

In [12]:
l2.sort(reverse=True)
print(l2)
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

2.9 Append 25 to the list.

In [13]:
l2.append(15)
l2
Out[13]:
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 15]

2.10 Append the numbers 99 and 80 to the list.

In [14]:
l2.extend([99, 80])
l2
Out[14]:
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 15, 99, 80]

2.11 Reverse the list.

In [15]:
l2.reverse()
l2
Out[15]:
[80, 99, 15, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

2.12 Create the following two sets: \begin{align*} m_1 &= \{1, 4, 23, 95, 12\}\\ m_2 &= \{0, 23, 80, 96, 95\}\\ \end{align*} What is the intersection of these sets?

In [16]:
m1 = {1, 4, 23, 95, 12}
m2 = {0, 23, 80, 96, 95}
m1 & m2
Out[16]:
{23, 95}

2.13 Create a dictionary with the following key-value pairs:

  • "Hello" and "Hola"
  • 5 and 120.5
  • "bla" and [10, 80]

Call the value of 'bla'.

In [17]:
d = {"Hello":"Hola", 5:120.5, "bla":[10,80]}
d["bla"]
Out[17]:
[10, 80]

Functions

2.1 Define a function that computes the following function:

$$f(x,y) = 10x+(1-y)^2$$
In [18]:
def f_xy(x, y):
    result = 10*x + (1-y)**2
    return(result)
f_xy(2,3)
Out[18]:
24

2.2. Extend the function such that it test whether its inputs are only numbers (int or float) Ergänzt die Funktion, sodass sie überprüft ob als Inputs nur Zahlen eingegeben wurden (int or float). If an input is no number, Python should raise an error.

In [20]:
def f_xy(x, y):
    assert (type(x) == int) | (type(y) == float), \
    "x is no number but {}".format(type(x))
    assert (isinstance(y, int)) | (isinstance(y, float)), \
    "y is no number but {}".format(type(x))
    result = 10*x + (1-y)**2
    return(result)
f_xy(2, "5")
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-20-5b04704bb6be> in <module>
      6     result = 10*x + (1-y)**2
      7     return(result)
----> 8 f_xy(2, "5")

<ipython-input-20-5b04704bb6be> in f_xy(x, y)
      3     "x is no number but {}".format(type(x))
      4     assert (isinstance(y, int)) | (isinstance(y, float)), \
----> 5     "y is no number but {}".format(type(x))
      6     result = 10*x + (1-y)**2
      7     return(result)

AssertionError: y is no number but <class 'int'>

Loops

3.1 Explain the difference between a for loop and a while loop.

In a for-loop your programm performs an action with inputs alongside a certain input container. In a while loop, a certain operation is repeated until a certain condition is met.

3.2 Create a list with the square roots of the numbers between 2 and 12. Provide a solution with a for loop and another using a list comprehension. Which solution is usually better?

In [21]:
l_for = []
for i in range(2, 13):
    l_for.append(i**0.5)
In [22]:
l_lcomp = [i**0.5 for i in range(2, 13)]

Because it is faster and usually more readable, a list comprehension should generally be preferred over a for loop.

3.3 The following loop does not work:

In [23]:
l_1 = [0, 2, "Land", "!"]
l_2 = ["Lame", "La", 1, 3]
for i in l_1:
    print(i * l_2[i], end=" ")
 2 
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-23-eb20b4769ea3> in <module>
      2 l_2 = ["Lame", "La", 1, 3]
      3 for i in l_1:
----> 4     print(i * l_2[i], end=" ")

TypeError: list indices must be integers or slices, not str

Adjust the code such that it does not iterate over the lements of l_1, but its indices.

Desired result: "LaLa Land!!!

In [24]:
l_1 = [0, 2, "Land", "!"]
l_2 = ["Lame", "La", 1, 3]
for i in range(len(l_1)):
    print(l_1[i] * l_2[i], end=" ")
 LaLa Land !!! 

3.4 How often does one need to raise $1.1$ to the power of 2 until the result is larger than 10? Answer this question using a while loop.

In [25]:
current_value = 1.1
counter = 0
while current_value <= 10:
    counter += 1
    current_value = current_value**2
print(counter, "iterations are required!")
5 iterations are required!

If-else

4.1 Translate the following into an if-else statement:

When x is an integer, print the adequate statement x equals two, x is smaller than two or x is bigger than two. When x is no integer, print the statemen x is no integer!.

In [26]:
x = "2"
if type(x)==int: 
    if x == 2:
        print("x equals two!")
    elif x < 2:
        print("x is smaller than two")
    elif x > 2:
        print("x is bigger than two")
    else:
        print("What he heck!?!?")
elif type(x)==str:
    print("Why would you compare strings with ints?")
Why would you compare strings with ints?

Imports and try-except blocks

5.1 Import pi from the math package and print it.

In [27]:
from math import pi
print(pi) 
3.141592653589793

or, better:

In [28]:
import math
print(math.pi)
3.141592653589793

5.2 Compute $\sqrt{2}$ using the function sqrt from the math package.

In [29]:
from math import sqrt
sqrt(2)
Out[29]:
1.4142135623730951

or, better:

In [30]:
import math
math.sqrt(2)
Out[30]:
1.4142135623730951

5.3 Build a try-except block in which you try to divide two variables, x and y, and in which you transform them into floats in case this operation leads to a TypeError.

In [31]:
x = "2"
y = 4
try:
    z = y / x
except TypeError:
    print("A type error occured. Try to resolve by converting x to float.")
    x = float(x)
    z = y / x
print(z)
A type error occured. Try to resolve by converting x to float.
2.0
In [ ]: