%%HTML
<link rel="stylesheet" type="text/css" href="https://raw.githubusercontent.com/malkaguillot/Foundations-in-Data-Science-and-Machine-Learning/refs/heads/main/docs/utils/custom.css">
%%HTML
<link rel="stylesheet" type="text/css" href="../utils/custom.css">
for loops (Concept 1)¶names = ["Guy", "Ray", "Tim"]
lower_names = [
names[0].lower(),
names[1].lower(),
names[2].lower(),
]
lower_names
['guy', 'ray', 'tim']
This code repetition is problematic
In many situations we want to do similar things multiple times
:for i in range(5):
print(i ** 2)
0 1 4 9 16
names = ["Guy", "Ray", "Tim"]
for name in names:
print(name.lower())
guy ray tim
let_to_pos = {
"a": 0,
"b": 1,
"c": 2,
}
for let in let_to_pos:
print(let)
a b c
.items() for looping over key/value pairsfor let, pos in let_to_pos.items():
print(let, pos)
a 0 b 1 c 2
if statements (Concept 2)¶if ,elif , and else are special keywordselif x: is the same aselse: + nested if x:number = -3.1
if number < -3:
clipped = -3.0
elif number > 3:
clipped = 3.0
else:
clipped = number
clipped
-3.0
if and elifFalse -ishbool(0)
False
True -ishbool(1)
True
False -ishbool([])
False
True -ishbool([1, 3])
True
andor (inclusive)nota = 3
b = 2
some_cutoff = 1
if a > b and b > some_cutoff:
print("do_something()")
else:
print("do_something_else()")
do_something()
names = ["Guy", "Ray", "Tim"]
names_with_i = []
for n in names:
if "i" in n:
names_with_i.append(n)
names_with_i
['Tim']
def keywordlowercase_with_underscores
)
def utility_crra(c, y=1.5):
return c ** (1 - y) / (1 - y)
utility_crra(1.0)
-2.0
utility_crra(1.0, y=0)
1.0
# bad example
global_msg = "Hello {}!"
def greet_with_global(name):
print(global_msg.format(name))
greet_with_global("Guido")
Hello Guido!
# solution 1: define inside function
def greet(name):
msg = "Hello {}!"
print(msg.format(name))
greet("Guido")
Hello Guido!
# solution 2: pass as argument
def greet_explicit(name, msg):
print(msg.format(name))
greet_explicit("Guido", "Hello {}!")
Hello Guido!
def append_4(some_list):
some_list.append(4)
return some_list
my_list = [1, 2, 3]
append_4(my_list)
my_list
[1, 2, 3, 4]
# better solution
def append_4(some_list):
out = some_list.copy()
out.append(4)
return out
pathlib¶pathlib?¶import pandas as pd
path = "C:\Users\xyz\Documents\python\lectures\03-more-python\data\iris.csv"
data = pd.read_csv(path)
Path(".") gives a relative
path to current directory
from pathlib import Path
# get a path to the current directory
this_dir = Path(".")
print(this_dir)
.
.resolve() makes it absolute for readability
this_dir = this_dir.resolve()
print(this_dir)
/Users/malka/Dropbox/teaching-uliege/Foundations-in-Data-Science-and-Machine-Learning/docs/m3
.parent moves up one
file/directory
# move up to the parent directory
root = this_dir.parent
print(root)
/Users/malka/Dropbox/teaching-uliege/Foundations-in-Data-Science-and-Machine-Learning/docs
In a Python script, you can use the following code to get a path to the project root:
from pathlib import Path
# get a path to the current file
this_file = Path(__file__)
print("this_file", this_file)
# move up several times (here twice) to the project root
root = this_file.parent.parent
print("root", root)
data_path = root / "data" / "iris.csv"
print("data", data_path)
print(data_path.exists())
data /Users/malka/Dropbox/teaching-uliege/Foundations-in-Data-Science-and-Machine-Learning/data/iris.csv True
Remember:
If you copy paste a path from your Windows File Explorer, all three rules are violated!