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

02 - Python Fundamentals - Introduction To Computation and Programming With Python

Uploaded by

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

02 - Python Fundamentals - Introduction To Computation and Programming With Python

Uploaded by

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

Introduction to Computation and Programming with

Python
Python 101 for Economists

José Moreno
Data Lead
1
2. Python Fundamentals

2
2. Python
Fundamentals
Installation and Environments

3
Python Installation

Windows Mac Linux


https://www.python.org/downloads/windows/ https://www.python.org/downloads/macos/ https://www.python.org/downloads/source/

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/

✓ Free, open-source code editor ✓ Online VS Code


✓ Rich ecosystem of extensions ✓ Cloud-based development environment
✓ Integrated terminal and debugger ✓ No local setup required
✓ Git integration ✓ Collaborative features
✓ Customizable and lightweight ✓ Integrated with Google Cloud
✓ Access your workspace from anywhere

5
Python Environments

What are Python Environments? Tips for Effective Environment Management

Isolated spaces where you can install packages


✓ Use a separate environment for each
and dependencies without affecting your
project
system-wide Python installation.
✓ Include a requirements.txt or
pyproject.toml in your project
✓ Avoid version conflicts between projects
✓ Regularly update your dependencies
✓ Easily share project dependencies
✓ Use version control (e.g., Git) to track
✓ Reproduce development environments
environment changes
✓ Document any specific setup steps in
your project's README

6
Poetry: Modern Dependency Management Intro

What are Python Environments?

Poetry is a tool for dependency management


and packaging in Python.

● Install Poetry. Check this installation


guide.
● Create a new project: poetry new
my-project
● Add dependencies: poetry add polars
● Activate environment: poetry shell

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
)

constants and lower for variables print_variables(


gross_domestic_product
=GROSS_DOMESTIC_PRODUCT
,
○ Be descriptive (as much as possible) unemployment_rate=UNEMPLOYMENT_RATE,
country_name=COUNTRY_NAME,
○ Avoid acronym (not gdp but is_developed_country
=IS_DEVELOPED_COUNTRY
gross_domestic_product ) )

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

● Represent True or False values


● Often used in conditional statements
● Capitalcase

Examples:

IS_DEVELOPED_COUNTRY = True
IS_IN_RECESSION = False

12
Data Types: None

● Represents the absence of a value (e.g., None)


● Often used in conditional statements
● Capitalcase

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

● and: True if both statements are true


● or: True if at least one statement is true
● not: Inverts the boolean value

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

Create variables and use operators to solve the following problem:

1. Create the following variables:


● Initial investment = 1000
● Annual interest rate = 5%
● Investment duration (in years) = 10
2. Perform the following calculations:
● Calculate and print the future value of the investment using the formula:

● 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.

⚠Homework: 1) String and Boolean Operators, 2) the effect of None in Operators


Generate a Google Docs in your folder with your research (before tomorrow 9:00)
17
2. Python
Fundamentals
Type hints introduction

18
What are Python Type Hints?

Annotations that specify the expected types of:


● Variables
● Function parameters
● Function return values

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.

● Efficiently store and manage data.


● Different types suited for different tasks.
● Key focus on Lists, Tuples, and Dictionaries.

23
Lists: Definition and Properties

● Ordered collection of items.


● Mutable (modifiable after creation).
● Can contain different data types (heterogeneous).
● Created using square brackets [].

fruits: list[str] = ["apple", "banana", "cherry"]


print(fruits[0]) # Output: apple

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

● Ordered collection of items.


● Immutable (cannot be changed after creation).
● Useful for fixed data structures.
● Created using parentheses ().

coordinates: tuple[int, int] = (10, 20)


print(coordinates[0]) # Output: 10

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

● Unordered collection of key-value pairs.


● Keys are unique, values can be any data type.
● Mutable (modifiable).
● Created using curly braces {}.

person: dict[str, Union[str, int]] = {"name": "José", "age": 35,


"city": "Barcelona"}
print(person["name"]) # Output: Alice

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

● Unordered collection of unique elements (no duplicates).


● Mutable (can add or remove items).
● Created using curly braces {} or set() constructor.

fruits: set[str] = {"apple", "banana", "cherry"}


print(fruits) # Output: {'apple', 'banana', 'cherry'}

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

Feature List Tuple Dictionary Set

Ordered Yes Yes No No

Mutable Yes No Yes Yes

Duplicate Elements Yes Yes No (key) No

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?

● Nesting allows you to store data structures within other data


structures.
● Real-world data often has mixed properties (ordered, unique,
key-value).
● Efficient data storage and management for complex tasks.
● Combining data structures unlocks even greater possibilities for data
organization and analysis.

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:

● Conditional Statements (if, elif, else): Conditional statements allow you to


execute different code blocks based on certain conditions.
● Loops (for, while): Loops allow you to repeat a block of code multiple times.

36
Conditional Statements

Statements that allow us to execute


different blocks of code based on
different conditions. if condition:
# code block

Types of Conditional Statements in elif another_condition:


e
Python: # code block
else:
● if statement # code block
● if-else statement
● if-elif-else statement
37
Loops

Statements that allow us to execute a


for item in sequence:
block of code repeatedly. e
# code block

Types of Loops in Python:

● for loop: iterates over a


sequence (e.g., list, tuple, string). while condition:
● while loop: repeats as long as a e
# code block
condition is True.

38
Loops: for vs while

Loop
Syntax How it Works Use Case Advantages Disadvantages
Type

Iterates over the When the number ● Simple and


for <variable>
elements of an of iterations is easy to read. Can only be used
For in <iterable>:
iterable (e.g., list, known ● Less prone to on iterables.
<code block>
tuple, string). beforehand. infinite loops.

● 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

A concise and expressive way to create a dictionary from a list or sequence


● They are often faster than traditional for loops.
● Syntax:[<expression> for <variable> in <iterable>
[if <condition>]]

squares = [x ** 2 for x in range(1, 11) if x % 2 == 0]

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.

● Syntax: enumerate(iterable, start=0)

fruits = ["apple", "banana", "orange"]


for index, fruit in enumerate(fruits):
print(index, fruit)

43
The zip function

A function that returns an iterator of tuples, combining elements from


multiple iterables.

● Syntax: zip(*iterables)

countries = ["France", "Japan", "Germany"]


prices = [12.99, 19.99, 3.50]
for country, price in zip(countries, prices):
print(f"{country}: ${price}")

44
2. Python
Fundamentals
Functions: definition, calling,
arguments, return values

45
Functions: Definition

● A function is a reusable block of code that performs a specific task.


● It helps to organize your code, make it more readable, and avoid code
duplication.
● Functions can take inputs (arguments) and produce outputs (return values).

def function_name (argument1, argument2, ...):


"""Docstring: Brief description of the function""" # Optional
# Function body (code to be executed)
return value # Optional

46
Functions: Definition

● Use the def keyword to define a function.


● A function name should be descriptive.
● Parameters are optional inputs that the function can accept.

def function_name (argument1, argument2, ...):


"""Docstring: Brief description of the function""" # Optional
# Function body (code to be executed)
return value # Optional

47
Functions: Calling

● To use a function, you need to call it by its name and ().


● You can provide arguments to the function when calling it in the ().

def greet(name: str) -> None:


"""Greets a person by name.
Args:
name (str): The name of the person to greet.
Returns:
None
"""
print(f"Hello, {name}!")

greet("Raul") # Output: Hello, Raul!

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

● Functions can return values using the return keyword.


● A function without a return statement returns None by default.
● The returned value can be used in other parts of your code.

def calculate_area (length: int, width: int) -> int:


area = length * width
return area

RECTANGLE_AREA = calculate_area (4, 6)


print(RECTANGLE_AREA ) # Output: 24

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:

is used. if not message:


message = "Welcome!"
● Optional arguments: When
if age:
combined with default arguments, print(f"{message}, {name}! I am

parameters can become optional, {age} years old.")


else:
providing flexibility in how the print(f"{message}, {name}!")
function is called.
greet_with_message()
● Rule: Default arguments must be
greet_with_message("Raul")
specified after non-default greet_with_message("Paula", "Hello")
arguments.
51
Functions: Summary and Best practices

Summary:

Functions are essential for writing reusable, modular, and clean code.

Best Practices:

● Use descriptive names.


● Avoid too many arguments.
● Use type hints for clarity.
● Document functions using docstrings.

52
2. Python
Fundamentals
Classes Basics

53
Classes: Definition

A class is a blueprint for creating objects


(instances).

Objects represent real-world entities with class ClassName :


attributes (data) and behaviors (methods). def __init__ (self, attributes ):
self.attributes = attributes

Key Concepts:

Attributes: Data associated with the object.


Methods: Functions that operate on the
object’s data.
54
Classes: Why Do We Use Classes?

● Encapsulation: Grouping related data


class Car:
and functions together. """A class representing a car."""
def __init__(
● Abstraction: Hiding the complexity
self,
and exposing only what is necessary. maker: str,
model: str
● Reusability: Code can be reused
):
through inheritance. self.maker = maker
self.model = model
● Modularity: Classes allow better code def display_info(self) -> None:
organization, especially for large print(f"Car: {self.maker} {self.model}")

projects.

55
Classes: Defining a Class in Python

● Use the class keyword followed by the class Person:


class name. """A class representing a person."""
def __init__(self, name: str, age: int):
● The __init__ method is the class self.name = name
constructor, which initializes the self.age = age

object’s attributes. def greet(self) -> None:

● 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

● Once a class is defined, you can create person = Person("José", 35)

objects (instances) from it. print(person.age)


● Access object attributes and call print(person.name)
methods using dot notation. person.greet()

57
Functions: Best Practices for Working with Classes
Summary:

● Classes provide structure to Python programs by bundling data and behavior.


● Object-Oriented Programming (OOP) is powerful for code reuse, modularity, and
maintaining large systems.
● Always aim to write clean, maintainable classes with meaningful names and responsibilities.

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.

● Importance: Essential for storing, retrieving, and analyzing data in Python


programs.
● Imagine: a spreadsheet containing economic data. File I/O allows you to
read this data into your Python program for analysis.

In Python, file I/O is done through built-in functions like open(), read(), and
write().

61
File Modes

● 'r': Read (default)


● 'w': Write (creates or overwrites)
● 'a': Append (adds data without deleting the existing content)
● 'b': Binary mode (for non-text files)
● '+': Read and write

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',

strings. encoding ="utf-8"


) as file:
file.writelines (content)

65
Handling Data with Python: CSV and JSON

● Python offers built-in support for reading and writing data in


CSV and JSON formats, two common file types for storing
structured data.
● Learning how to work with these file formats is crucial for
economists when dealing with datasets like trade data, survey
responses, and more.

66
Reading csv files

def read_csv_file(file_path: str) -> List[Dict[str,


Any]]:
data: List[Dict[str, Any]] = []
try:
with open(file_path, mode='r', newline='',
Python's csv module provides encoding='utf-8') as csvfile:
csv_reader = csv.DictReader(csvfile)
functionality to handle csv files
for row in csv_reader:
reading: csv.DicReader. data.append(dict(row))
except FileNotFoundError:
print(f"The file {file_path} does not exist.")
return data

67
Reading json files

def read_json_file(file_path: str) ->


List[Dict[str, Any]]:
data: List[Dict[str, Any]] = []
try:
Python's json module provides with open(file_path, 'r', encoding='utf-8')
as file:
functionality to handle json files: data = json.load(file)

json.load. except FileNotFoundError:


print(f"The file {file_path} does not
exist.")
return data

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="",

csv.DictWriter. encoding="utf-8") as csvfile:


writer = csv.DictWriter(csvfile,
fieldnames=fieldnames)
writer.writeheader()
writer.writerows(list_of_dictionaries)

69
Writing json files

def write_json(file_path: str, data:


Dict[str, Any]) -> None:
"""Writes a dictionary to a JSON
Python's json module provides file."""

functionality to handle json files: with open(file_path, mode='w',


encoding='utf-8') as file:
json.dump.
json.dump(data, file, indent=4)

70

You might also like