Week 1 — Introduction to Programming

Programming and Numerical Methods for Economics (ECNM10115) · The University of Edinburgh

Python Essentials

Learning goals. After this notebook you can: create lists and NumPy arrays; use loops, conditionals, and functions; and solve your first real exercises from QuantEcon.

How to use this notebook: run every cell (Shift+Enter), and for each exercise write your own attempt before opening the solution. Programming is learned through the fingers, not the eyes.

If you’ve never used Python before, start with the Python refresher (PS0) on the course page.

Import libraries

By convention, numpy (numerical computing) is imported as np and matplotlib.pyplot (plotting) as plt.

import numpy as np
import matplotlib.pyplot as plt

On good coding practices

Python has a philosophy — run this:

import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Lists

A list holds an ordered collection of items — numbers, strings, anything.

list_1 = [1, 2, 3]
list_2 = ['Boris', 'Laura', 'Robert']

print(list_1)
print(list_2)
print(list_1[0])     # indexing starts at ZERO in Python!
[1, 2, 3]
['Boris', 'Laura', 'Robert']
1

Quick check ✋ — before you run the next cell: what will list_1[0] print, 1 or 2?

Answer 1 — Python indexes from zero, unlike MATLAB or R. This will bite you at least once this semester.

Arrays

NumPy arrays are how we do maths. A 2-D array is a matrix:

\[ \begin{bmatrix} 0 & 1 & 0 \\ 0 & 1 & 1 \\ \end{bmatrix} \]

A = np.array([[0,1,0],[0,1,1]])  # create the 2-D array — i.e. matrix

# Procedural approach: call the np.mean function on A.
m1_A = np.mean(A)

# Object-oriented approach: call the array's own .mean() method.
m2_A = A.mean()

# Python does not automatically display everything we compute (as Stata does) —
# we call print() when we want to see something.
print(m1_A)
print(m2_A)
0.5
0.5

Some operations

x = [4.6, 10, 2]
print(max(x))          # the largest element
print(list(range(3)))  # range(n) generates 0, 1, ..., n-1
10
[0, 1, 2]

Boolean values

True/False values power all the logic in your programs — and they behave like 1/0 in arithmetic, which is a trick we use constantly.

bools = True, False, True
print(all(bools))   # are ALL of them True?
print(any(bools))   # is ANY of them True?
print(True + True)  # booleans behave like 1 and 0!
False
True
2

Exercises (from QuantEcon)

Now you. Each exercise has an empty cell for your attempt and a hidden solution. Attempt first — struggling for ten minutes teaches you more than reading the answer for one.

Exercise 1 — Inner product

Compute the inner product of x_vals and y_vals using a loop: multiply the lists element by element and collect the results.

Predict first: what is 2×10 + 4×3 + ...? Roughly what numbers should appear in your list?

x_vals = [2, 4, 3, 5, 0]
y_vals = [10, 3, 2, 9, 8]

# Your attempt here:
💡 Click to reveal the solution — but try it yourself first!
inner_vals = []
for x, y in zip(x_vals, y_vals):   # zip loops through the two lists in tandem
    inner = x * y
    inner_vals.append(inner)       # appending (storing) results in a list
print(inner_vals)
Expected output: [20, 12, 6, 45, 0]

Exercise 2 — Count the even numbers in 0–99

Hint: % is the remainder operator, so x % 2 == 0 tests whether x is even. Remember booleans add like 1s and 0s.

# Your attempt here:
💡 Click to reveal the solution — but try it yourself first!
count = 0
for x in range(100):          # for-loop over 0..99
    even_yes = (x % 2 == 0)   # remainder operator + comparison
    count += even_yes         # booleans add as 1/0
print(count)
Expected output: 50

Exercise 3 — Count pairs where both numbers are even

Given pairs = ((2,5), (4,2), (9,8), (12,10)), count how many pairs have both numbers even.

pairs = ((2,5), (4,2), (9,8), (12,10))

# Your attempt here:
💡 Click to reveal the solution — but try it yourself first!
count = 0
for x, y in pairs:
    count += (x % 2 == 0 and y % 2 == 0)   # 'and' logical operator
print(count)
Expected output: 2 — the pairs (4,2) and (12,10).

Exercise 4 — Compute \(\int_0^2 x^3 \, dx\)

Your first taste of numerical methods! Use quad from SciPy, the main library for numerical analysis. (Check yourself with the analytical answer: \(\frac{x^4}{4}\Big|_0^2 = 4\).)

from scipy.integrate import quad   # SciPy's definite-integral routine

# Your attempt here:
💡 Click to reveal the solution — but try it yourself first!
fx = lambda x: x**3          # lambda creates a one-line function
                             # in Python, the power operator is **
fx_area = quad(fx, 0, 2)     # compute the definite integral

print('The area of x^3 on [0,2] is', fx_area[0])
Expected output: 4.0 — matching the analytical answer.

Exercise 5 — Evaluate a polynomial

Write a function polynomial(x, coeff) that computes \(a_0 + a_1 x + a_2 x^2 + \dots\) for a list of coefficients. Test it with coeff = [1, 2, 1] (that is, \(1 + 2x + x^2\)) at \(x = 2\).

# Your attempt here:
💡 Click to reveal the solution — but try it yourself first!
def polynomial(x, coeff):
    poly = 0
    for i, a in enumerate(coeff):   # enumerate gives you (index, value) pairs
        poly += a * x**i
    return poly

print(polynomial(2, [1, 1]))        # 1 + x        -> 3
print(polynomial(2, [1, 2, 1]))     # 1 + 2x + x^2 -> 9
print(polynomial(2, [1, 2, 2, 1]))  # 1 + 2x + 2x^2 + x^3 -> 21

Exercise 6 — Count capital letters

Write a function that counts the number of capital letters in a string. Test it on 'The Rain in Spain is Wet'.

Hint: letter.upper() turns a letter into upper case, and letter.isalpha() tells you whether a character is a letter at all.

# Your attempt here:
💡 Click to reveal the solution — but try it yourself first!
def count_capitals(string):
    count = 0
    for letter in string:
        if letter == letter.upper() and letter.isalpha():
            count += 1
    return count

print(count_capitals('The Rain in Spain is Wet'))
Expected output: 4 — T, R, S, W.

Self-check quiz

Answer in your head, then click to check.

Q1. What does range(5) produce?
Answer 0, 1, 2, 3, 4 — five numbers, starting at zero, stopping before 5.
Q2. What is True + False + True?
Answer 2 — booleans behave like 1 and 0 in arithmetic.
Q3. A.mean() and np.mean(A) — which one is the object-oriented style?
Answer A.mean() — you call the method that belongs to the array object itself.

Before next week

  • Finish any exercise you didn’t complete — bring questions to the lab.
  • If Python is new to you, work through PS0 (the Python refresher) on the course page.
  • Skim the QuantEcon Python programming lectures — lectures 1–3 mirror what we did today.

Next week: fundamentals of programming in Python — data types, control flow, and writing serious functions.