--- jupytext: text_representation: extension: .md format_name: myst kernelspec: display_name: Python 3 language: python name: python3 --- (python_by_example)= ```{raw} html
``` # An Introductory Example ```{index} single: Python; Introductory Example ``` ```{contents} Contents :depth: 2 ``` ## Overview We're now ready to start learning the Python language itself. In this lecture, we will write and then pick apart small Python programs. The objective is to introduce you to basic Python syntax and data structures. Deeper concepts will be covered in later lectures. You should have read the {doc}`lecture
```
The Python interpreter performs the following:
* For each element of the `sequence`, it "binds" the name `variable_name` to that element and then executes the code block.
The `sequence` object can in fact be a very general object, as we'll see
soon enough.
### A Comment on Indentation
```{index} single: Python; Indentation
```
In discussing the `for` loop, we explained that the code blocks being looped over are delimited by indentation.
In fact, in Python, **all** code blocks (i.e., those occurring inside loops, if clauses, function definitions, etc.) are delimited by indentation.
Thus, unlike most other languages, whitespace in Python code affects the output of the program.
Once you get used to it, this is a good thing: It
* forces clean, consistent indentation, improving readability
* removes clutter, such as the brackets or end statements used in other languages
On the other hand, it takes a bit of care to get right, so please remember:
* The line before the start of a code block always ends in a colon
* `for i in range(10):`
* `if x > y:`
* `while x < 100:`
* etc., etc.
* All lines in a code block **must have the same amount of indentation**.
* The Python standard is 4 spaces, and that's what you should use.
### While Loops
```{index} single: Python; While loop
```
The `for` loop is the most common technique for iteration in Python.
But, for the purpose of illustration, let's modify {ref}`the program above ` to use a `while` loop instead.
(whileloopprog)=
```{code-cell} python3
ts_length = 100
ϵ_values = []
i = 0
while i < ts_length:
e = np.random.randn()
ϵ_values.append(e)
i = i + 1
plt.plot(ϵ_values)
plt.show()
```
Note that
* the code block for the `while` loop is again delimited only by indentation
* the statement `i = i + 1` can be replaced by `i += 1`
## Another Application
Let's do one more application before we turn to exercises.
In this application, we plot the balance of a bank account over time.
There are no withdraws over the time period, the last date of which is denoted
by $T$.
The initial balance is $b_0$ and the interest rate is $r$.
The balance updates from period $t$ to $t+1$ according to $b_{t+1} = (1 + r) b_t$.
In the code below, we generate and plot the sequence $b_0, b_1, \ldots, b_T$.
Instead of using a Python list to store this sequence, we will use a NumPy
array.
```{code-cell} python3
r = 0.025 # interest rate
T = 50 # end date
b = np.empty(T+1) # an empty NumPy array, to store all b_t
b[0] = 10 # initial balance
for t in range(T):
b[t+1] = (1 + r) * b[t]
plt.plot(b, label='bank balance')
plt.legend()
plt.show()
```
The statement `b = np.empty(T+1)` allocates storage in memory for `T+1`
(floating point) numbers.
These numbers are filled in by the `for` loop.
Allocating memory at the start is more efficient than using a Python list and
`append`, since the latter must repeatedly ask for storage space from the
operating system.
Notice that we added a legend to the plot --- a feature you will be asked to
use in the exercises.
## Exercises
Now we turn to exercises. It is important that you complete them before
continuing, since they present new concepts we will need.
### Exercise 1
Your first task is to simulate and plot the correlated time series
$$
x_{t+1} = \alpha \, x_t + \epsilon_{t+1}
\quad \text{where} \quad
x_0 = 0
\quad \text{and} \quad t = 0,\ldots,T
$$
The sequence of shocks $\{\epsilon_t\}$ is assumed to be IID and standard normal.
In your solution, restrict your import statements to
```{code-cell} python3
import numpy as np
import matplotlib.pyplot as plt
```
Set $T=200$ and $\alpha = 0.9$.
### Exercise 2
Starting with your solution to exercise 2, plot three simulated time series,
one for each of the cases $\alpha=0$, $\alpha=0.8$ and $\alpha=0.98$.
Use a `for` loop to step through the $\alpha$ values.
If you can, add a legend, to help distinguish between the three time series.
Hints:
* If you call the `plot()` function multiple times before calling `show()`, all of the lines you produce will end up on the same figure.
* For the legend, noted that the expression `'foo' + str(42)` evaluates to `'foo42'`.
### Exercise 3
Similar to the previous exercises, plot the time series
$$
x_{t+1} = \alpha \, |x_t| + \epsilon_{t+1}
\quad \text{where} \quad
x_0 = 0
\quad \text{and} \quad t = 0,\ldots,T
$$
Use $T=200$, $\alpha = 0.9$ and $\{\epsilon_t\}$ as before.
Search online for a function that can be used to compute the absolute value $|x_t|$.
### Exercise 4
One important aspect of essentially all programming languages is branching and
conditions.
In Python, conditions are usually implemented with if--else syntax.
Here's an example, that prints -1 for each negative number in an array and 1
for each nonnegative number
```{code-cell} python3
numbers = [-9, 2.3, -11, 0]
```
```{code-cell} python3
for x in numbers:
if x < 0:
print(-1)
else:
print(1)
```
Now, write a new solution to Exercise 3 that does not use an existing function
to compute the absolute value.
Replace this existing function with an if--else condition.
(pbe_ex3)=
### Exercise 5
Here's a harder exercise, that takes some thought and planning.
The task is to compute an approximation to $\pi$ using [Monte Carlo](https://en.wikipedia.org/wiki/Monte_Carlo_method).
Use no imports besides
```{code-cell} python3
import numpy as np
```
Your hints are as follows:
* If $U$ is a bivariate uniform random variable on the unit square $(0, 1)^2$, then the probability that $U$ lies in a subset $B$ of $(0,1)^2$ is equal to the area of $B$.
* If $U_1,\ldots,U_n$ are IID copies of $U$, then, as $n$ gets large, the fraction that falls in $B$, converges to the probability of landing in $B$.
* For a circle, $area = \pi * radius^2$.
## Solutions
### Exercise 1
Here's one solution.
```{code-cell} python3
α = 0.9
T = 200
x = np.empty(T+1)
x[0] = 0
for t in range(T):
x[t+1] = α * x[t] + np.random.randn()
plt.plot(x)
plt.show()
```
### Exercise 2
```{code-cell} python3
α_values = [0.0, 0.8, 0.98]
T = 200
x = np.empty(T+1)
for α in α_values:
x[0] = 0
for t in range(T):
x[t+1] = α * x[t] + np.random.randn()
plt.plot(x, label=f'$\\alpha = {α}$')
plt.legend()
plt.show()
```
### Exercise 3
Here's one solution:
```{code-cell} python3
α = 0.9
T = 200
x = np.empty(T+1)
x[0] = 0
for t in range(T):
x[t+1] = α * np.abs(x[t]) + np.random.randn()
plt.plot(x)
plt.show()
```
### Exercise 4
Here's one way:
```{code-cell} python3
α = 0.9
T = 200
x = np.empty(T+1)
x[0] = 0
for t in range(T):
if x[t] < 0:
abs_x = - x[t]
else:
abs_x = x[t]
x[t+1] = α * abs_x + np.random.randn()
plt.plot(x)
plt.show()
```
Here's a shorter way to write the same thing:
```{code-cell} python3
α = 0.9
T = 200
x = np.empty(T+1)
x[0] = 0
for t in range(T):
abs_x = - x[t] if x[t] < 0 else x[t]
x[t+1] = α * abs_x + np.random.randn()
plt.plot(x)
plt.show()
```
### Exercise 5
Consider the circle of diameter 1 embedded in the unit square.
Let $A$ be its area and let $r=1/2$ be its radius.
If we know $\pi$ then we can compute $A$ via
$A = \pi r^2$.
But here the point is to compute $\pi$, which we can do by
$\pi = A / r^2$.
Summary: If we can estimate the area of a circle with diameter 1, then dividing
by $r^2 = (1/2)^2 = 1/4$ gives an estimate of $\pi$.
We estimate the area by sampling bivariate uniforms and looking at the
fraction that falls into the circle.
```{code-cell} python3
n = 100000
count = 0
for i in range(n):
u, v = np.random.uniform(), np.random.uniform()
d = np.sqrt((u - 0.5)**2 + (v - 0.5)**2)
if d < 0.5:
count += 1
area_estimate = count / n
print(area_estimate * 4) # dividing by radius**2
```