02 - Python Fundamentals - Introduction To Computation and Programming With Python
02 - Python Fundamentals - Introduction To Computation and Programming With Python
Python
Python 101 for Economists
José Moreno
Data Lead
1
2. Python Fundamentals
2
2. Python
Fundamentals
Installation and Environments
3
Python Installation
Via Installer
● Download the installer ● Download the installer ● Most distros come with
● Open the installer and ● Open the installer and Python
follow the instructions follow the instructions
● If not, use package manager.
● PATH (select the default ● Verify: python --version
E.g., Ubuntu: sudo apt-get
option) install python3
Via Brew
● Verify: python --version
● Install brew
● Run: brew Install Python
● Verify: python --version
4
Development Editors (for lectures)
VS Code IDX
https://code.visualstudio.com/download https://idx.google.com/
5
Python Environments
6
Poetry: Modern Dependency Management Intro
7
2. Python
Fundamentals
Basic syntax: variables, data
types and operators
8
Variables in Python
GDP = 1000000000000
GROSS_DOMESTIC_PRODUCT= 1000000000000
UNEMPLOYMENT_RATE = 5.2
● Variables are containers for storing data values COUNTRY_NAME = "United States"
IS_DEVELOPED_COUNTRY= True
● Python is dynamically typed (no need to declare
def print_variables(
variable type, but we will use type hints!) gross_domestic_product
: int,
unemployment_rate: float,
● Naming conventions: country_name: str,
is_developed_country
: bool
○ Start with a letter or underscore ) -> None:
print(gross_domestic_product
)
○ Can contain letters, numbers, underscores print(unemployment_rate)
print(country_name)
○ Case-sensitive, use UPPER case for code print(is_developed_country
)
9
Data Types: Numbers
1. Integers (int)
● Whole numbers, positive or negative
Example: YEAR = 2024
2. Floating-point numbers (float)
● Numbers with decimal points
Example: INFLATION_RATE = 2.5
3. Complex numbers
● Numbers with real and imaginary parts
Example: Z = 3 + 2j
10
Data Types: Strings
● Sequences of characters
● Enclosed in single ('') or double ("") quotes
Examples:
COUNTRY = "France"
CURRENCY = 'Euro'
MESSAGE = "The economy is growing"
11
Data Types: Booleans
Examples:
IS_DEVELOPED_COUNTRY = True
IS_IN_RECESSION = False
12
Data Types: None
Example:
EMPTY_VALUE = None
13
Operators: Arithmetic
● Addition: +
● Subtraction: -
● Multiplication: *
● Division: /
● Floor division: //
● Modulus: %
● Exponentiation: **
14
Operators: Comparison
● Equal to: ==
● Not equal to: !=
● Greater than: >
● Less than: <
● Greater than or equal to: >=
● Less than or equal to: <=
15
Operators: Logical
16
Apply what we have learned (15 min)
First pseudo code in paper, then upload python code to your folder (e.g. u138478), name variables_future_value.py
● Check if the investment has doubled and print the result as a boolean value.
● Has the investment doubled AND is the future value greater than $2500? Print the result.
● Has the investment doubled OR is the future value greater than $2100? Print the result.
18
What are Python Type Hints?
They were introduced in Python 3.5 (PEP 484).They do not affect runtime behavior
(they are "hints", not enforced rules).
19
Why are Type Hints Important?
● Code Clarity: Makes intentions clear to other developers (and future you!)
● Error Prevention: Catches type-related errors early in development
● Better IDE Support: Enables better autocomplete and refactoring tools
● Documentation: Serves as inline documentation for expected types
● Easier Refactoring: Makes large-scale code changes safer
● Improved Static Analysis: Allows for more thorough code checks without
running the program
20
How to use them on VSCode?
{
"python.analysis.typeCheckingMode": "strict",
"python.analysis.diagnosticSeverityOverrides": {
"reportUnknownMemberType": false
}
}
21
2. Python
Fundamentals
Data structures: lists, tuples,
dictionaries and sets
22
Data Structures Intro
Python data structures are essentially containers for different kinds of data.
23
Lists: Definition and Properties
24
Lists: Common Operations
● Access: fruits[1]
● Append: fruits.append("orange")
● Remove: fruits.remove("banana")
● Length: len(fruits)
● Slice: fruits[1:3]
25
Tuples: Definition and Properties
26
Tuples: Common Operations
● Access: coordinates[1]
● Concatenation: new_tuple = coordinates + (30, 40)
● Length: len(coordinates)
● Tuples are immutable, so no append/remove.
27
Dictionaries: Definition and Properties
28
Dictionaries: Common Operations
● Access: person["age"]
● Add: person["profession"] = "Economist"
● Modify: person["age"] = 36
● Remove: del person["city"]
● Keys and values: person.keys(), person.values(),
person.items()
29
Sets: Definition and Properties
30
Sets: Common Operations
● Add: unique_fruits.add("orange")
● Remove: unique_fruits.remove("banana")
● Union: set1.union(set2)
● Intersection: set1.intersection(set2)
● Difference: set1.difference(set2)
● Is subset: set1.issubset(set2)
31
Sets vs Lists vs Tuples vs Dictionaries
Use case Dynamic data Fixed Data Key-value pairs Unique elements
32
Nested Data Structures
Python allows us to combine basic data structures to create more complex ones.
Common combinations include:
● Lists of tuples
● Dictionaries with list values
● Sets of tuples
● Dictionaries with tuple keys
● Etc
💡Choose the right combination based on your data's structure and access
patterns
33
Nested Data Structures: Why?
34
2. Python
Fundamentals
Control flow: conditional
statements, loops
35
Control Flows
Control flow determines the order in which individual statements, instructions, or
function calls are executed in Python.
By default, statements are executed sequentially, one after the other. Control flow
statements allow us to deviate from this sequential order.
Key components:
36
Conditional Statements
38
Loops: for vs while
Loop
Syntax How it Works Use Case Advantages Disadvantages
Type
● More flexible
More prone to
Executes the code When the stopping than for loops.
while infinite loops if
block repeatedly condition is ● Can be used to
While <condition>: the condition is
as long as the dynamic or execute a
<code block> not updated
condition is True. uncertain. block of code
correctly.
indefinitely.
39
List Comprehension
40
Dictionary, Sets and Tuples Comprehension
A concise and expressive way to create a dictionary, a set or a tuple from a
sequence.
# Dictionary comprehensions
squares = {x: x ** 2 for x in range(1, 11) if x % 2 == 0}
# Set comprehensions
evens = {x for x in range(1, 11) if x % 2 == 0}
# Tuple comprehensions
tuples = [(x, x + 1) for x in range(10) if x % 2 == 0]
41
Comprehension advantages
Advantages
● Speed: List comprehensions can be significantly faster than traditional for loops,
especially for large lists.
● Conciseness (elegance): List comprehensions can be written in fewer lines of code
than traditional for loops.
● Easy filtering.
Disadvantages
● Readability Issues: Overly complex comprehensions can make code hard to read,
especially when nested.
● Not Ideal for Complex Logic: Comprehensions are harder to maintain when the logic
grows more complex (e.g., multiple conditions or transformations).
42
The enumerate function
A function that returns an iterator of tuples containing the index and value
of each element in a sequence.
43
The zip function
● Syntax: zip(*iterables)
44
2. Python
Fundamentals
Functions: definition, calling,
arguments, return values
45
Functions: Definition
46
Functions: Definition
47
Functions: Calling
48
Functions: Arguments
● Arguments are values passed to a function when it's called. They can be used
inside the function to perform calculations or modify data.
● Functions can have zero, one, or more arguments.
● They can be mandatory or optionals.
● Usage:
○ Positional arguments: Arguments passed in the same order as the
function parameters.
○ Keyword arguments: Arguments passed with the parameter name
(useful when dealing with many arguments). I recommend to use this
always!!!!
49
Functions: Return Values
50
Functions: Default and Optional Arguments
● Default arguments: Allow you to def greet_with_message(
define a default value for a name: str = "Guest",
message: str = "",
parameter. If no value is passed
age: Optional[int] = None
during the function call, the default ) -> None:
Summary:
Functions are essential for writing reusable, modular, and clean code.
Best Practices:
52
2. Python
Fundamentals
Classes Basics
53
Classes: Definition
Key Concepts:
projects.
55
Classes: Defining a Class in Python
● You can add all the methods you need. print(f"Hello, my name is {self.name}
and I am {self.age} years old.")
But if you have too many maybe your
class has too many responsibilities. person = Person("José", 35)
person.greet()
56
Classes: Creating and Using Objects
57
Functions: Best Practices for Working with Classes
Summary:
Best Practices:
● Use meaningful class names: Class names should describe the object clearly (e.g., Car,
Person).
● Keep it simple: Classes should follow the Single Responsibility Principle (SRP)—each class
should have one purpose.
58
2. Python
Fundamentals
File I/O: Reading and Writing
Data in Python
59
What is a file?
A file is a contiguous set of bytes used to store data. This data is organized in a
specific format and can be anything as simple as a text file or as complicated as a
program executable.
Files on most modern file systems are composed of three main parts:
● Header: metadata about the contents of the file (file name, size, type, and so on)
● Data: contents of the file as written by the creator or editor
● End of file (EOF): special character that indicates the end of the file
Source: https://realpython.com/read-write-files-python/
60
File I/O (Input/Output)
It refers to the process of reading data from files and writing data to files.
In Python, file I/O is done through built-in functions like open(), read(), and
write().
61
File Modes
62
File I/O Flow
def open_file_flow(
file_name: str,
1. Open a file.
mode: str
2. Perform read or write operations. ) -> None:
file = open(
3. Close the file to free resources. file_name,
You can use context managers mode,
encoding="utf-8"
(with statements, the common )
way). # Perform read/write operations here
file.close() # Always close the file
63
File Read
def read_file(
file_name: str
● read(): Reads the entire content
) -> List[str]:
as a string. with open(
● readline(): Reads one line at a file=file_name,
time. mode='r',
encoding="utf-8"
● readlines(): Returns all lines as ) as file:
a list of strings. content = file.readlines()
return content
64
File Write
def write_file (
file_name : str,
content: List[str]
● write(): Writes a string to the ) -> None:
with open(
file.
file=file_name ,
● writelines(): Writes a list of mode='w',
65
Handling Data with Python: CSV and JSON
66
Reading csv files
67
Reading json files
68
Writing csv files
def write_csv(
list_of_dictionaries: List[Dict[str, Any]],
file_path: str
Python's csv module provides ) -> None:
fieldnames = list_of_dictionaries[0].keys()
functionality to handle csv files: with open(file_path, "w", newline="",
69
Writing json files
70