0% found this document useful (0 votes)
8 views

Topic_1_Getting_Started

The document outlines the syllabus and structure for the course 'Python Programming for Economics' (Econ 2048) taught by Dr. Marcus Roel at UNNC in Spring 2024. It emphasizes learning coding fundamentals rather than specific Python modules relevant to economics, with a focus on practical coding exercises and a final written exam for grading. The course is designed for beginners with no prior coding experience, encouraging collaboration and exploration of coding projects.

Uploaded by

James SI
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Topic_1_Getting_Started

The document outlines the syllabus and structure for the course 'Python Programming for Economics' (Econ 2048) taught by Dr. Marcus Roel at UNNC in Spring 2024. It emphasizes learning coding fundamentals rather than specific Python modules relevant to economics, with a focus on practical coding exercises and a final written exam for grading. The course is designed for beginners with no prior coding experience, encouraging collaboration and exploration of coding projects.

Uploaded by

James SI
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

In [22]: # Comment this cell out if you want cells to span your whole screen

from IPython.display import display, HTML


display(HTML("<style>:root { --jp-notebook-max-width: 75% !important; } </st

Python Programming for Economics


(Econ 2048)
Dr. Marcus Roel
Spring 2024, UNNC

Econ 2048
This course is about learning how to code (decently)
Hopefull fun - with many practical (and some pointless) examples
I want you to play with code, try out little projects, etc.
Get together with a classmate and write (small) stuff (possibly beyond our
course material)
Target audience: you don't know anything about coding : ).
if you know a little, that's fine too.

Organizational Stuff
Lecturer: Dr Marcus Roel
Email: [email protected]
Office Hours: Tuesdays 11:30-13:30, IEB369 (no appointment needed)
Lecture Times: Thursdays 9-11am in DB-C05 (+ Q&A after class)

Syllabus
Today: Basic syntax, functions, control flow
Topic 2: List (data container) and Loops (repeating tasks); Start with coding the
children game "Hangman"
Topic 3: Coding Better; more on functions, and more cool syntax
Topic 4: Load modules, read from and write/save to files; simulations with random
variables
Topic 5: Classes (how & use cases)
Syllabus
Topic 6: Writing decent code. the Zen of Python, PEP8, Google Style Guide, Clean
Code DRY, Loose Coupling, Robustness
Topic 7: Other useful syntax, memory management and computing times
Topic 8: Errors and Exception Handling (how to deal with errors, etc.)
All code for the spring 2024 was written and tested in Python 3.12 (on MacOS 14.1)
Syllabus
Emphasis on learning general coding skills that are transferable across programming
languages
I opted against teaching you particular python modules that are relevant to Econ,
e.g., numpy, pandas, matplotlib!
don't take this course if this is what you expect to learn.
(slim chance we cover them in the last week if time permits)
Instead, we will do quite a few longer homework projects
A better foundation is much more important than knowing a few extra modules
(Economists write awful, time-wasting code)
If you know how to code, this is NOT your course
Grading.
100% of your overall grade comes from a final written exam (2 hours).
pure pen & paper
closed book
Seminars.
First seminar next week: problem set and getting python working
Problem Sets.
You can find practice questions at the end of each lecture set!
I expect you to go over them. We will cover (most of) them the following week!
In [ ]:

Reading List
There is none.
See Syllabus on Moodle for detailled suggestions
One word of caution: if you read a book alongside, check what python version they
use

Plan for Today


How to write some basic Python expressions, assignments & functions
"Text Coding"
Code Flow (sequential, if-clauses)
Install Python, Jupyther Notebooks
Some Python Background
To code alongside and try out things for the first day, use: https://www.online-
python.com
(we'll sort out the advanced stuff later)

Python Coding - Let's get straight into it!


In [1]: x = 1
y = 2
z = x + y

print(z) # prints the value of the variable z.

# Text following "#" is a comment. It will not be "executed"


# Comments are great! Use them a lot - especially as you learn!
#
# You can start a line with a comment, or
# add it 'in-line' to right of existing code
# (2 spaces between code and "#")

Quick comment on the length of "comments", which look rather short


Convention: limit all lines to a maximum of 79 characters
I keep them shorter due to the way code is presented in slides
Note, this will violate our conventions in topic 6
Calculate 1 + 2 + 3 + … + 10
In [2]: y = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
print(y)

55

In [6]: # A slightly better solution


x_max = 10
sum_series = (x_max+1) * (x_max/2) # 1+10, 2+9, 3+8 all equal 11.
print(sum_series)

55.0

Order Precendence
the order of mathematical operations follow our usual rules
parenthesis
exponents
multiplication and division
addition and substraction
and for completeness (we will learn these later)
comparisons (as well as is , in , not is , not in )
negation ( not )
and
or
if you're in doubt, always use a parenthesis, especially since it improves readabilty
Datatypes: Numbers
You will typically encounter three different types of numbers
Whole numbers (-1, 0, 1, 2, etc.): integers, called int
Floating point numbers (3.5, 7.3333, etc.), called float
Complex numbers (3 + i), called complex
Unlike other programming languages, you do not need to tell python what type of
number you want upon assignment
In general, stick to integers whenever you can (the default for numbers without ".")
Floating point numbers have fundamental precision problems
e.g., 1.5 may at times become 1.50000101 - without you realizing
problematic when you check whether two numbers are equal
https://docs.python.org/3/tutorial/floatingpoint.html
In [4]: x = 2 # int
y = 3.14 # float, i.e., any digit
y2 = 3. # Also float
y3 = 6 / 3 # Result of a division is always a float.
z = 1j # complex
z2 = complex(3,4) # 3 is the real, 4 is the imaginary part.

# We can check datatypes with the type() command


# We will revisit what a 'class' is.
print(x, 'is of type: ', type(x))
print(y, 'is of type: ', type(y))
print(y2, 'is of type: ', type(y2))
print(y3, 'is of type: ', type(y3))
print(z, 'is of type: ', type(z))

2 is of type: <class 'int'>


3.14 is of type: <class 'float'>
3.0 is of type: <class 'float'>
2.0 is of type: <class 'float'>
1j is of type: <class 'complex'>

Functions: generalizing code!


In [5]: def sum_sequence(x_min, x_max):
# x_min, x_max are your typical variables (arguments)
sum_series = (x_min+x_max) * (x_max-x_min+1)/2
return sum_series

result = sum_sequence(1,10) # Assign result of function call to variable re

# Print multiple items by adding comma.


print("1 + 2 + ... + 10 =", result)

# Note: you can execute the function directly in the print command. Try:
# print("1 + 2 + ... + 10 =", sum_sequence(1,10))

1 + 2 + ... + 10 = 55.0

def sum_sequence(x_min, x_max):


sum_series = (x_min+x_max) * (x_max-x_min+1)/2
return sum_series

A function is defined by the keyword def followed by the function name.


In parenthesis, we introduced two arguments, x_min , x_max .
The code block that defines what the function does is indented by 4 spaces/1 tab
(tabs are usually automatically converted to 4 spaces in coding environments)
The function returns a value, e.g., the sum of the sequence
To call / excecute a function, simply write its name and plug in values for its
arguments
In [2]: # Functions don't always have to return values
# nor do they require arguments.

def hello_world(): # Always requires a parenthesis


text_to_print = "Hello World." # strings (text) are assigned via " " o
print(text_to_print)
# End of function - simply end the tab; add newline.
# Calling your magical function
hello_world()

Hello World.

Return Values of Functions


our math function sum_sequence returns a value
hello_world does not (use the return keyword)

For math problems, we may want to use the calculated "result" again for more
calculations.
Hence, for most math-like functions (and indeed many other functions), the
function should give us the result back (i.e., return)
hello_world, has one job, namely to prints a text to our screen. Once that is done, it's
done. There is nothing we want more from it
the return keyword is therefore optional when you define a function.
HOWEVER, when the function arrives at the return keyword, it stops. Nothing
afterwards gets computed!
In [8]: # The function hello_world() is really 'dumb' - it can't do much.
# Let's give it "some functionality".

def hello_world_2(text):
text_1 = "Hello World. "
to_print = text_1 + text # Combine text by "addition".
print(to_print)

hello_world_2("Hello Class!")

Hello World. Hello Class!

A quick comment on combining texts


You can combine two pieces of text via addition
In [7]: text_1 = "Hello "
text_2 = "course"

text_3 = text_1 + text_2


print(text_3)

Hello course
Hello course ECON2048

But you cannot combine text and numbers by addition


Python doesn't know what you want it to 'do', e.g., should the text be considered
number or the number be considered a text?
In this case, use str() to convert a number into a string
In [9]: text = "This is Econ" + str(2048)
print(text)

# Of course, in this particular case, it's much easier to just say


# text = "This is Econ2048"

This is Econ2048

Some advanced remarks (can be skipped)


A function that doesn't return anything returns the object "None"
To call a function, you must use function_name()
calling function_name without the () doesn't run the function. It creates a
link to the function (which in turn can be called again); very advanced.
For iPython Notebook Users: you must always "run" the cell that defines a function,
e.g., hello_world(), before you can call it in a different cell. (problem often happens
when you come back to an existing file)

Feel free to skip these comments (especially if they seem like foreign language). But
some of you may find them helpful when playing around with the code.
In [11]: # A function that doesn't return anything returns "None"

# The Function gets executed, and its result assigned to return_value


return_value = hello_world()

print('Return value of hello world is:', return_value)

Hello World.
Return value of hello world is: None

Functions
Functions typically solve a class of problems, i.e., they are "algorithms"
sum_sequence is a useful function, hello_world maybe not so much
If you need to do a similar things more than once, turn it a function.
Don't Repeat Yourself (DRY) when you code
Sketching Code / Faking Coding
It's a good idea to not worry about the specific code syntax at first when you try to
write something new
Just like sketching out an essay, we can sketch out code, filling in the blanks later
For example, let's write out a function that programs your morning routine
Version 1.
my morning routine.
get out of bed
wash face
brush teeth
go to kitchen
make coffee
eat breakfast
shower
go to work

Version 2. (a bit more code-like; not better or worse than Version 1)

def my_morning_routine():
get_out_of_bed()
wash_face()
brush_teeth()
go_to_kitchen()
make_coffee()
eat_breakfast()
shower()
go_to_work()

Observations Morning Routine


With a bit of logic and abstraction, we can all "code" like this
Where have we seen this type of code before?
Recipes, Instruction manuals, Driving instructions, etc.
Currently, very barebone: how much coffee? what breakfast?
Purely sequential code, going line by line.
No means to skip, vary, etc.
Notice also how in version 2, I am calling functions (which implement each tasks)
If Statements
Ideally, the first thing we want to adjust in the morning routine is: workday vs.
weekend, i.e.
if workday, then go to work
if weekend, then go out and play

or (don't tell my partner)


if there are cookies in the house, eat cookies for breakfast
if there aren't cookies, eat oats for breakfast

There is nothing particular wrong about the current way of writing:


if workday, then go to work
if weekend, then go out and play

But since it's either workday or weekend, we can just check the condition once
if workday, go to work, otherwise go out and play

If/else conditions
if [a statement that is either true of false]:
do_something()
else:
do_something_else_instead()

In [8]: x = 5
y = 6

if x > y:
print(x, 'is bigger than', y)
else:
print(x, 'is not bigger than', y)

5 is not bigger than 6

If/elif/else conditions
What if we actually want to check if x is bigger, equal, or smaller than y?
When there are more than 2 possibilities, we can use

if [statement that is either true of false]:


do_something()
elif [statement that is either true of false]:
do_something_else_1()
elif [statement that is either true of false]:
do_something_else_2()
...
else:
do_something_else_n()
Note: if any if (elif, the python syntax for "else if") is true, nothing below it is
checked.
In [9]: # If, elif, else example.

x = 5
y = 6

if x > y:
print(x, 'is bigger than', y)
elif x == y:
print(x, 'is equal to', y)
else:
print(x, 'is not bigger than', y)

5 is not bigger than 6

Booleans (or just bools)


So far, you have learned two datatypes: text (strings) and numbers (int, float,
complex)
Another datatype are boleans: True or False (case sensitive!)
any comparison, say x == y, x > y, x >= y, x != y (not equal to) returns a bool
"==" can be used for most objects, e.g., whether the content of a string equals
another
comparison can be chained with
and : true if and only if both statements are true*
or : true if at least one statements is true
comparison/booleans can be negated with not
In [10]: # booleans examples
print('5 > 7: ', 5 > 7)

5 > 7: False

In [11]: # booleans examples, continued


print('5 < 7 and 5 < 10: ', 5 < 7 and 5 < 10)
print('5 < 7 or 5 > 10: ', 5 < 7 and 5 > 10)

5 < 7 and 5 < 10: True


5 < 7 or 5 > 10: False

In [12]: # booleans examples, continued

x = 5 > 7 # You can assign comparisons to variables!


print('not 5 > 7: ', not x)

not 5 > 7: True

input() function.
Python has many built in functions
For now, we will code many exiting functions ourselves (point is to learn to
code)
One very cool function is input() which asks the user to input some text during
runtime
This allows you to write interactive code.
indeed, you can write entire text-based games with this alone
In [13]: # input() function

# Use "." around the string if you need to use a ' in the text.
print("Hi there. What's your name?")
name = input()

# f'strings! Add `f` before a string in order to place variables


# directly into the text using {}
print(f"Hi {name}. Nice to meet you!")

Hi there. What's your name?


Hi x. Nice to meet you!

Installing Python
Install Python
My preferred method: download Python from https://www.python.org/downloads/
and install.
Install Jupyter Notebook (recommended for now; see next slide)
Install any IDE (PyCharm, Visual Studio, etc.) and run code directly from IDE (more
advanced. not necessarily better, especially when starting out. only recommended if
you know someone who can teach you)
Jupyter Notebook
This is what we use for the lectures (in the beginning)
Install via python installer called "pip".
HOW:
1. Open terminal/cmd environment
(MacOS): either type "terminal" in spotlight search or open via
applications>utilities>terminal
(Windows) start>windows system> command or cmd.exe
2. type pip3 install notebook (the 3 in pip is for python3)
After the installation, you can open the notebook app (which will run in your browser) by:
Open terminal/cmd and type jupyter notebook
Better: run it by immediately setting your preferred directory, e.g.: jupyter
notebook --notebook-dir="/Users/m_roel/Teaching/Python
Programming for Econ/"

Alternative Installation Path


install the Python scientific stack via Anaconda
It includes both the core Python interpreter and most packages required for
data analysis.
You can open Ipython Notebooks directly via a visual button from Anaconda's
Interface
After the installation of Anaconda, packages can be installed by opening
Anaconda PowerShell Prompt and run, for example: `conda install seaborn'
In [14]: # https://learn.microsoft.com/en-us/windows/python/beginners for troublesho
# https://packaging.python.org/en/latest/tutorials/installing-packages/

Jupyter Notebook
A Jupyter notebook is divided into individual, vertically arranged cells, which can be
executed separately.
Cells in Jupyter notebook are of three types − Code, Markdown and Raw.
We can write Python statements in a code cell. When such cell is run, its result is
displayed in an output area of the code cell.
Markdown cells contain text formatted using markdown language, and are especially
useful to provide documentation to the computational process of the notebook.
Contents in raw cells are not evaluated by notebook kernel.
In this module, the slides are written using Jupyter Notebook.

Python
Background (non-examinable)
Python is a popular general–purpose programming language.
Console applications
GUI applications (there is better)
Website development
Data analysis
AI / Deep Learning
According to the ranking on TIOBE, Python has become the most popular
programming language in the world.
Used extensively for data analysis, such as statistics, econometrics and machine
learning.
Relatively easy to learn.
Fast to code (but that doesn't mean we should be lazy)
Reasons to Use Python
Fast to write, especially with available open-source packages, and the easiest
language to learn
A live-language (gets updated regularly)
Versatility
Allows access to web-based services, database servers, data management and
processing and statistical computation
Write server-side apps, apps for desktop-class operating systems with
graphical user interfaces, or apps for tablets and phones apps
Data handling and manipulation
Cleaning and reformatting
More capable at data set construction than either R or MATLAB
Knowledge of Python, as a general purpose language, is complementary to
R/MATLAB/Stata - or - C#, C++, Java, etc.
In general, good programmers can code in many languages - depending on the task
at hand (don't write games in Python)
Python in Science
NumPy: a set of array data types which are essential for statistics, econometrics
and data analysis
Pandas: high-performance data structures; essential when working with data
SciPy: routines for analysis of data, including random number generators, linear
algebra routines, and optimizers
Matplotlib: lotting environment for 2D plots (and some 3D support)
Seaborn: improves the default appearance of matplotlib plots without any additional
code
Statsmodels: provides models used in the statistical analysis of data including linear
regression, Generalized Linear Models (GLMs), and time-series models (e.g.,
ARIMA); works with pandas
Jupyter Notebook an interactive Python environment in a web-browser based
notebook
Comparison to Popular "Econ" Alternatives
R
Provides comprehensive statistics library
At the forefront of new statistical algorithm development
Limited support on performance optimization
MATLAB
Provides a wide range of algorithms
Commercial support is provided
Modules are well documented and organized
Stata
Popular for eonometric analysis
Programmable but not primarily a programming language (coding anything
complex is a pain!)
Focuses more on making complex data analysis easily accessible
My person go-to for basic analysis (fast, easy, latex add-ons)
Homework
standard-homework: go over our examples from the lecture and (1) understand
them, and (2) vary them slightly to see if you really understand them.
Write your own morning routine, evening routine, or any other task sequence that
you do.
You can do this for literally everything you do. Feel free to be creative : )
Write a function that (a) adds two numbers, (b) multiplies 3 numbers with each
other, and (c) computers some other mathematical problem (e.g., the length of the
hypotenuse in a right triangle?) of your liking.
Write a function takes subtracts the second argument from the first if both
arguments are positive. It returns 0 if one or both arguments are negative. (hint:
if/then clause)
use the print() function to write some fun things to your screen.
if you combine more than one string variable, pay particular attention to spa
In [ ]: Suggestions: solve a typical (simple) math problem that you face in your oth

Homework
Turn the following if-check into a function that compares two inputs.

x = 5
y = 6

if x > y:
print(x, 'is bigger than', y)
else:
print(x, 'is not bigger than', y)

Homework
Write a function that uses input() and a if/else comparison.
Homework Using simple language only (no coding yet) write one (or more) functions to
describe the popular children's game "hang-man"
i.e., guess letters from a secret word (of a known length). You must guess it fully
before missing 7 times.
If you find this easy, try it with the game "Wordle"
Click here for hint

You might also like