# Exercises to Lecture 2: Introduction to Python 3.6 
By Dr. Anders S. Christensen
`anders.christensen @ unibas.ch`


## Exercise 2.1: define a function

One of the fundamental things we learned was how to define functions.

For example, the function defined below `square(x)` calculates the square, $x^2$:


```
def square(x):
  y = 2 * x**2
  return y

print(square(2))
```

    8


### Question 2.1.1:

Similarly to the above code, make a function called. for example, `poly(x)` to calculate the following polynomial:
\begin{equation}
p\left( x \right) = 5 x^2 - 4x + 1
\end{equation}

Lastly, print the value of $p\left( 5 \right)$


```
def poly(x):

  # Fill out the rest of the function yourself!
  p = 5* x**2  - 4*x + 1

  return p
  

# Print the value for x=5
print(poly(5))
```

    106


## Exercise 2.2: Loop within function

The code below implements the product of all numbers up to n, i.e. the factorial function "$!$"

\begin{equation}
f(n) = n! = \prod_{i=1}^n i = 1 \cdot 2 \cdot \quad  ... \quad \cdot (n -1) \cdot n
\end{equation}

As an example, the code to calculate $5!$ is shown here:


```
n = 5

f = 1
for i in range(1,n+1):
  f =  f * i

print("Factorial", n, "is", f)
```

    Factorial 5 is 120


### Question 2.2.1

Unfortunately the above code is not very practical and re-usable, and will only work for $n=5$. Instead we would like a function named `factorial(n)`. In this Exercise, write your own function which calculates the factorial.

As output print `factorial(10)`.


```
def factorial(n):
  
  # Write the rest of the function yourself
  f = 1
  for i in range(1,n+1):
    f =  f * i
  
  return f

print(factorial(10))
```

    3628800


### Question 2.2.2:

Using the `factorial(n)` function you wrote in the previous question, print all $n!$ for all n from 1 to 20. 

Hint: Use another for loop!


```
# Below, write the code to print all n! from n=1 to n=20

for n in range(1, 21):

  print(n, factorial(n))


```

    1 1
    2 2
    3 6
    4 24
    5 120
    6 720
    7 5040
    8 40320
    9 362880
    10 3628800
    11 39916800
    12 479001600
    13 6227020800
    14 87178291200
    15 1307674368000
    16 20922789888000
    17 355687428096000
    18 6402373705728000
    19 121645100408832000
    20 2432902008176640000


## Exercise 2.3: `if` / `else` statements

`if` and `else` statments can are used to make decisions based on defined criteria.


```
n = 10

if n < 10: 
  print("n is less than 10")
else:
  print("n is greater than 10")


```

### Question 2.3.1:

One example of mathematical functions that contain such statements are the so-called "rectifier linear unit" (ReLU) functions which are often used in Neural Networks.

An example is given here:
\begin{equation}
f\left(x\right) =
\begin{cases} 
      0 & x\leq 0 \\
      x & x \gt 0 
   \end{cases}
\end{equation}

In this question, write the above ReLU function, which returns $0$ if $x \leq 0$ and returns $x$ otherwise.

Lastly, verify the correctness of your code your code using the 5 print statments in the code block below.


```
def relu(x):

  # Implement the content of the ReLU function yourself!
  if x <= 0.0:
    return 0.0
  else:
    return x


print(relu(-10))  # should return 0
print(relu(-0.1)) # should return 0
print(relu(0))    # should return 0
print(relu(0.1))  # should return 0.1
print(relu(10))   # should return 10
```

    0.0
    0.0
    0.0
    0.1
    10


## Exercise 2.4: Plotting

In the below example, the value of
 $$y= x^2$$ 
 is calculated for six values of $x$, and appended to a list.

Next, the points are plottet using the `plt.plot()` function from the `pyplot` library.

The function `plt.plot()` tells matplotlib to draw a lineplot that connects all the pairs of points in two lists.


```
import matplotlib.pyplot as plt

# Some x-values
x = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]

# Initialize an empty list for the y-values we wish to plot
y = []

for i in range(len(x)):

  # Calculate the square of each x in the list
  value = x[i]**2

  # Add the calculated value to the list "y"
  y.append(value)

# Print the two lists
print(x)
print(y)

# Make a line plot/figure
plt.plot(x, y)

# Actually draw the figure below
plt.show()
```

### Question 2.4.1:

Instead of plotting a line through all points, it is also possible to plot datapoints using a so-called [scatterplot](https://en.wikipedia.org/wiki/Scatter_plot).

For this behavior, you can replace the function `plt.plot()` in the above example with the function `plt.scatter()`.

In this question you are given two lists of numbers below, `a` and `b`.

Use pyplot to draw a *scatterplot* of the two lists.


```
a = [10.0, 8.0, 13.0, 9.0, 11.0, 14.0, 6.0, 4.0, 12.0, 7.0, 5.0]
b = [8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84, 4.82, 5.68]

# Here, write the code to show a scatterplot for the lists a, b
plt.scatter(a, b)
plt.show()
```

### Question 2.4.2:

In order to give the plot a title and label the axes, insert the three functions in the code in Question 2.4.1:

*    `plt.xlabel()`
*    `plt.ylabel()`
*    `plt.title()`

Make the plot title "Python 2020", label the x-axis "Apples" and the y-axis "Oranges"


```
plt.scatter(a, b)
plt.xlabel("Apples")
plt.ylabel("Oranges")
plt.title("Python 2020")
plt.show()
```

## Exercise 2.5: More plotting (harder) 


### Question 2.5.1:
In the example in Problem 2.4, the code for a line plot for $y = x^2$ is shown.

Write your own code to plot $y = \cos(x)$ from 0 to 10.

**Hints:**


*   Import the `np.cos()` function using `import numpy as np`
*   If the figure does not look smooth, how can you make the points on the x-axis closer than 1.0?





```
# First try:
# Note that there are many ways to solve this exercise!

import numpy as np

x = []
y = []

for i in range(11):
  x.append(i)
  y.append(np.cos(i))

# Print the two lists to verify that you have the right numbers
print(x)
print(y)

# Make the figure
plt.plot(x, y)

# Actually draw the figure below
plt.show()
```


```
# Smooth, with more x-values:
# Note that there are many ways to solve this exercise!

import numpy as np

x = []
y = []

for i in range(100):

  # Now there are 100 points between 0 and 10 with 0.1 spacing
  # => smoother curve
  xval = i/10.0
  x.append(xval)

  yval = np.cos(xval)
  y.append(yval)


# Print the two lists to verify that you have the right numbers
print(x)
print(y)

# Make the figure
plt.plot(x, y)

# Actually draw the figure below
plt.show()
```

b2e2bd740aeccd14489cb7fc5103bc2bae3f210d
ipynb
Jupyter Notebook
intro_exercises2_solutions_2020.ipynb
andersx/python-intro
8409c89da7dd9cea21e3702a0f0f47aae816eb58
CC0-1.0
2020-05-03T11:59:01.000Z
2021-11-15T12:33:39.000Z
intro_exercises2_solutions_2020.ipynb
andersx/python-intro
8409c89da7dd9cea21e3702a0f0f47aae816eb58
CC0-1.0
intro_exercises2_solutions_2020.ipynb
andersx/python-intro
8409c89da7dd9cea21e3702a0f0f47aae816eb58
CC0-1.0
2020-05-10T21:15:15.000Z
2021-12-05T15:13:54.000Z
Qwen/Qwen-72B
1. YES
2. YES