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

02 - Python Fundamentals

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)
10 views

02 - Python Fundamentals

Uploaded by

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

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,
sets and dictionaries

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

You might also like