You’ll be able to:
help(), the internet, AI tutorsYou’ll be able to:
You’ll be able to:
You’ll be able to:
Introduction
The composition of sequences of instructions, called programs, that computers can follow to perform tasks. — Wikipedia
(and also design, testing, debugging, maintenance…)
The art of programming is the art of organizing complexity. — Edsger Dijkstra.
Any fool can write code that a computer can understand. Good programmers write code that humans can understand. — Martin Fowler
What about no-code, low-code and AI generated code?
Low/no-code raises the floor. Code removes the ceiling.
if value > threshold: reject reads like a decision, not a program; focus on ideas, not punctuationU0 Introduction
U1 Development environment: uv, Jupyter, Anaconda
U2 Variables, I/O, data types and type conversion
U3 Making decisions: conditionals and boolean logic
U4 Lists and tuples: slicing, unpacking
U5 Loops and flow control
U6 Dictionaries and comprehensions
U7 Functions: scope, lambda, args
U8 map, filter and pandas masks
U9 Modules and packages
U10 Files: text, binary, JSON, pathlib
U11 Exceptions and tracebacks
U12 Intro to classes & OOP
U13 Debugging tools and methods
| Session | Duration | Units |
|---|---|---|
| 1 | 2h | U0 – U3 |
| 2 | 3h | U4 – U7 |
| 3 | 3h | U8 – U13 |
Each session opens with the learning outcomes of its units and closes with their recaps.
Trying and failing , and trying again. Nothing beats experience.
Python has a help function. Type help(anything) and you can read documentation on it.
The internet is your friend. Search for errors and desired functionality. Stack Overflow is a solid resource.
Reading other people’s code is a great way to learn (if it’s good code)
AI may be good for learning - use the Socratic method.
Example of a recommended prompt
Act as my Socratic tutor on Python programming
[or some other topic, e.g., UI building with Gradio, Async/Await, PyTorch].
- Never provide direct code solutions unless I ask for
a specific syntax example.
- Ask one question at a time to guide me to the answer,
starting with simple concepts and building up to complex ones.
- If I am stuck, offer a small hint or an analogy rather than the code.
- If I make a mistake, prompt me to run a test case or identify
the contradiction in my reasoning.
- Wait for my input after every question."Development environment
pip, venv, …macOS / Linux (Terminal):
Windows (PowerShell):
Close and reopen the terminal, then check it worked:
More options in the uv installation docs.
Windows without admin rights, or the command is blocked? Follow this guide.
uv init to initialize the project
pyproject.toml – project description + list of dependencies.python-version – which Python version the project usesmain.py, README.md – starter files.venv/ and uv.lock appear after the first uv add / uv run.venv/ folderpandas 2.x while project B stays on 1.x.venv/ by hand: uv manages it for you.venv, installs the packagepyproject.tomlStart JupyterLab:
uv run runs a command inside the project environmentuv run uses the project’s venv automatically. To type python or jupyter lab directly instead, activate the venv first (from the project folder):
macOS / Linux:
Windows (PowerShell):
(aaiml-python)python, pip, jupyter lab now use the project’s venvdeactivate to leaveuv run (details)| Command | What it does |
|---|---|
uv init |
start a new project in the current folder |
uv add <pkg> |
install a package and record it |
uv remove <pkg> |
uninstall a package |
uv run <cmd> |
run a command/script in the project env, e.g. uv run python main.py |
uv sync |
recreate the env from pyproject.toml (e.g. on another computer) |
uv tree |
show the project’s packages and what they depend on |
uv python list |
show available/installed Python versions |
source .venv/bin/activate |
activate the venv (Windows: .venv\Scripts\activate) |
Tip: inside a notebook started with uv run jupyter lab, you can install packages with !uv add <pkg>.
.py file and run the whole file.ipynb) mixes code, results, text and plots in one document| Cell type | Contains | Run it with |
|---|---|---|
| Code | Python code; output appears below the cell | Shift+Enter |
| Markdown | formatted text: titles, lists, equations | Shift+Enter |
[3] next to a cell is the order it ran in; cells can run in any order, so the state may not match top-to-bottom readingYou only need one of them.
Prefer a graphical installer with everything bundled? Anaconda is the alternative.
Anaconda is a popular open-source Python distribution that makes it easy to install Python and many data science libraries.
This link will take you to the Anaconda download page. Download Anaconda for your operating system.
Amazon SageMaker provides an extensive set of tools to develop the complete lifecycle of a ML solution.
It provides a managed Jupyter Notebook service, i.e. running on remote servers (AWS).
Beware of running processes after no longer in use, because of associated costs. Small mistakes can cost a lot of money.
Another managed Jupyter Notebook provider is Google Colab.
Google Colab is a free Jupyter Notebook provider that will allow you to run code on Google’s servers, using only CPUs. Execution with GPUs is paid.
From now on, it’s assumed you have a functional Python environment.
Go on and open a Jupyter Notebook to follow along.
Variables, I/O and data types
print and inputint vs float, operationsstr: concatenation, formatting f"pi={3.1415}", string methodsTrue and Falsefloat("3.14")A variable is a placeholder for some value.
Think of it like a drawer where you can put anything you want and retrieve it later.
Let’s create some variables.
accuracy, num_samples and model_name are all variables.
The = operator assigns a value (any value) to the variable.
We can also assign the value of a variable to another variable.
previous_accuracy now has the value of accuracy, which is 0.87
And we can overwrite the value of an existing variable.
The value of accuracy is now 0.91 instead of 0.87.
But previous_accuracy is still 0.87!
We can retrieve the value of a variable, simply by typing its name.
We’re retrieving the value of accuracy and then assigning it to another variable.
How to interact with the outside of our program?
print - send values to userinput - receive values from userprint will write some text to the terminal/screen.
The print function will comes in handy to check the values of variables.
If we feed it a non text value, it will try to convert it to text first.
We can also print several values at once, if we separate them with commas.
After executing the input function, the terminal will wait for user input.
The user can write whatever she wishes, ending with an enter.
The input function can receive an optional string that is printed to the terminal before receiving input from the user.
We’ve already seen some values of different kinds.
Do you remember which?
Both train_split and num_samples are numeric types, but they’re not the same.
The type function will tell us the type of any value we give it.
train_split is a float (as in floating point number), the representation of a real number.
num_samples is an int (as in integer), the representation a natural number including negative numbers.
str (short for string) is how we represent text.
str is another basic type in Python.
It’s used to encode text like dataset names, column names, labels.
bool (short for boolean) encodes a True or False value.
Many operations, like comparisons between two values, will return a True or False value.
Operations: + - * / // % **
Conversion
💻 Let’s see in practice! 💻
How can we deal with text? Strings!
String methods
Formatted strings
Conversion
💻 Back to the code! 💻
Making decisions
if / elif / elseand or vs. & |import packages, e.g. import pandasIn Python, indentation defines structure — there are no { } (like in C, for example)
Use 4 spaces, or a consistent tab, per level. Mixing them causes errors.
Modern editors allow configuration and usually fix mixing.
A program has very limited functionality if it’s not able to make decisions.
Conditionals enable us to execute a portion of code based on some decision.
What is happening here?
if StatementIn Python, we state conditionals with the if statement.
We’re checking if new_accuracy meets our deployment threshold of 0.9.
If it is, the comparison operator (>=) will return True, otherwise False.
When the condition after if is True, the program will execute the code that is indented forward.
Here, that code is in line 4.
The else statement allows us to define code to be executed when the condition fails.
Here, that code is in line 6.
Conditions are usually built by comparing values. The result is always a bool.
| Operator | Meaning | Example | Result |
|---|---|---|---|
== |
equal to | model_name == "LogisticRegression" |
True |
!= |
not equal to | num_samples != 1000 |
False |
< |
less than | 0.87 < 0.9 |
True |
> |
greater than | 0.87 > 0.9 |
False |
<= |
less than or equal to | num_samples <= 1000 |
True |
>= |
greater than or equal to | 0.92 >= 0.9 |
True |
= assigns a value, == compares two values.
new_accuracy = 0.88
champion_accuracy = 0.87
decision = None
if new_accuracy >= champion_accuracy + 0.02:
decision = "deploy new model"
elif new_accuracy >= champion_accuracy - 0.01:
decision = "retrain and monitor"
elif new_accuracy >= 0.80:
decision = "collect more data"
else:
# below minimum threshold
decision = "discard model"We can also chain several conditions with elif.
elif works like else, but it allows us to define more conditions.
new_accuracy = 0.88
champion_accuracy = 0.87
decision = None
if new_accuracy >= champion_accuracy + 0.02:
decision = "deploy new model"
elif new_accuracy >= champion_accuracy - 0.01:
decision = "retrain and monitor"
elif new_accuracy >= 0.80:
decision = "collect more data"
else:
# below minimum threshold
decision = "discard model"When chaining conditions in this way, a given condition is only processed if all the previous conditions fail.
new_accuracy = 0.88
champion_accuracy = 0.87
decision = None
if new_accuracy >= champion_accuracy + 0.02:
decision = "deploy new model"
elif new_accuracy >= champion_accuracy - 0.01:
decision = "retrain and monitor"
elif new_accuracy >= 0.80:
decision = "collect more data"
else:
# below minimum threshold
decision = "discard model"The condition on line 6 will only be processed if the condition on line 5 fails.
new_accuracy = 0.88
champion_accuracy = 0.87
decision = None
if new_accuracy >= champion_accuracy + 0.02:
decision = "deploy new model"
elif new_accuracy >= champion_accuracy - 0.01:
decision = "retrain and monitor"
elif new_accuracy >= 0.80:
decision = "collect more data"
else:
# below minimum threshold
decision = "discard model"The condition on line 8 will only be processed if the conditions on lines 5 and 7 fail.
new_accuracy = 0.88
champion_accuracy = 0.87
decision = None
if new_accuracy >= champion_accuracy + 0.02:
decision = "deploy new model"
elif new_accuracy >= champion_accuracy - 0.01:
decision = "retrain and monitor"
elif new_accuracy >= 0.80:
decision = "collect more data"
else:
# below minimum threshold
decision = "discard model"The final else statement will only be processed if the conditions on lines 5, 7 and 8 fail.
Comments are not code, they’re just extra information the programmer adds to the program so it’s easier to understand the code.
Comments are never executed, even if they contain valid code.
Combine conditions with:
a and b → result is True, if both arguments are True
a or b → result is True, if any of the arguments is True
not a → if a was True, it is now False, and vice versa.
patience = 15 # confit param
# these two variables would come from the
# current iteration of a training run
accuracy = 0.88
epoch = 30
# these two variables would come from the
# best past iteration of a training run
best_accuracy = 0.87
best_epoch = 24
decision = None
if accuracy < best_accuracy and epoch - best_epoch >= patience:
decision = "stop training"
elif accuracy >= best_accuracy:
# continue training
best_accuracy = accuracy
best_epoch = epoch
# there is no else in this exampleUseful for filter masks.
Animations from Real Python
>>>) and running scripts (uv run python main.py).venv), activationuv treeuv add / pip installprint and input"a string" and 'also a string', concatenation, formatting f"pi={3.1415}"True and Falsefloat("3.14")if / elif / elseand or vs. & |import packages to our programs, e.g. import pandas
Comments
#is the start of a comment in Python.