Topic_1_Getting_Started
Topic_1_Getting_Started
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
55
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.
# 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
Hello World.
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 course
Hello course ECON2048
This is Econ2048
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"
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
def my_morning_routine():
get_out_of_bed()
wash_face()
brush_teeth()
go_to_kitchen()
make_coffee()
eat_breakfast()
shower()
go_to_work()
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)
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
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 > 7: False
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()
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/"
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