Module 02: Jupyter Notebooks, Control Flow, and Functions

September 16, 2026

Intro to Scientific Python

Content covered:

  1. Saving Your Work with Git
  2. Jupyter Notebooks
  3. Control Flow
  4. Built-in Functions
  5. Functions
  6. Bringing it all together
Intro to Scientific Python

By the end of this class, you will be able to:

  • Fork a repository and configure origin/upstream remotes
  • Save and track your own work on a branch with git switch -c, git add, git commit, and git log
  • Use .gitignore
  • Create and run code in a Jupyter Notebook
  • Write conditional logic and loops
  • Call built-in functions
  • Define and call functions
Intro to Scientific Python

1. Saving Your Work with Git

Intro to Scientific Python

Forking the Repo

Forking creates your own copy of a repository under your own GitHub namespace. You can commit to it, branch it, and manage it independently of the original.

Let's fork the course repo now:

https://github.com/datalus-dev/gsk-intro-scientific-python-course

Click Fork in the top right.

Intro to Scientific Python

Adding upstream

Right now your origin remote points at the course repo (datalus-dev). That's what you cloned in Module 1.

git remote -v

Convention: the repo you forked from, the one you pull course updates from, is called upstream. Let's add it, pointing at the same place origin currently does:

git remote add upstream https://github.com/datalus-dev/gsk-intro-scientific-python-course.git
Intro to Scientific Python

Repointing origin to Your Fork

Now that upstream covers the course repo, let's repoint origin at your fork instead:

git remote set-url origin https://github.com/<your-username>/gsk-intro-scientific-python-course.git
git remote -v

You should now see origin → your fork, upstream → the course repo.

Intro to Scientific Python

Keep Your Work off main

Your main branch should always match the course repo, so that pulling course updates stays simple.

Before you commit your own work, create a branch called personal and switch to it:

git switch -c personal

This is where you'll save your notes for the rest of the class. We'll cover branches in more depth in Module 4.

Intro to Scientific Python

git add and git commit

Staging tells git which changes to include in your next snapshot:

git add <file>

Committing saves that snapshot with a message:

git commit -m "A short description of what changed"
Intro to Scientific Python

git log

See the history of commits:

git log
Intro to Scientific Python

.gitignore

Some files shouldn't be tracked, e.g. build artifacts, environments, caches. .gitignore tells git to skip them.

Here's this course repo's own .gitignore:

cat .gitignore

Why do you think _build/, .ipynb_checkpoints, and *.pdf are ignored here?

Intro to Scientific Python

2. Jupyter Notebooks

Intro to Scientific Python

From ipython to Notebooks

Last class we ran Python interactively in the terminal with ipython:
one line in, one result out, nothing saved.

A notebook lets you save your work in one place. You can mix your prose with code.

Intro to Scientific Python

Cells

A notebook is made of cells:

  • Code cells — Python you run with Shift+Enter
  • Markdown cells — formatted text, headers, notes, explanations of what you did and why

Order matters: cells run in the order you run them, not top to bottom automatically. This is a common source of bugs.

Intro to Scientific Python

Open Today's Notebook

We'll use this notebook, module_02.ipynb, for the rest of class.

Shortcuts you'll want:

  • Esc then a / b — add a cell above / below
  • Esc then m — change the current cell to Markdown
  • Esc then y — change the current cell to code
Intro to Scientific Python

Try it live

Intro to Scientific Python

Markdown Cells

Change a cell's type to Markdown (Esc then m, or the toolbar dropdown) to write formatted notes. Your notebook already has a couple — take a look.

This is how you'll document your homework and final project notebooks — narrate what you did, not just show code.

Intro to Scientific Python

Running Notebooks Locally

For the lectures, I'm running JupyterLite so I can embed Python into my slides. It's great for demos but we'll be setting things up locally. For your own machine:

cd ~/workspace/gsk-intro-scientific-python-course
conda activate gsk
jupyter lab

This opens the full Jupyter Lab interface, backed by your actual conda environment (not the browser sandbox).

Open notebooks/module_02.ipynb from the file browser. This is the copy you'll save with git.

Intro to Scientific Python

Discussion

Q: What's an advantage of a notebook over a plain script?

Q: What's a risk of running cells out of order?

Intro to Scientific Python

3. Control Flow

Intro to Scientific Python

Truthiness

Every object in Python has a boolean value, even if it's not a bool.

Falsy by default:

  • None and False
  • zero of any numeric type: 0, 0.0, 0j
  • empty sequences and collections: '', (), [], {}, set(), range(0)

Everything else is truthy.

Intro to Scientific Python

Comparison Operators

Operation Meaning
< strictly less than
<= less than or equal
> strictly greater than
>= greater than or equal
== equal
!= not equal
Intro to Scientific Python

if / elif / else

Python uses indentation (spaces), not parentheses or braces, to mark a conditional's scope.

if 5 > 6:
    print("the universe is broken")
elif len("cat") > len("dog"):
    print("uh oh, something is wrong in the world")
else:
    print("math is still mathing")

if runs when true, elif checks next, else catches everything else.

Intro to Scientific Python

Try it live

Add this to module_02.ipynb:

x = 7
if x < 0:
    print("negative")
elif x == 0:
    print("zero")
else:
    print("positive")

% gives the remainder after division, so we can use it to check for even and odd numbers:

if x % 2 == 0:
    print("even")
else:
    print("odd")
Intro to Scientific Python

Try it live, cont.

Intro to Scientific Python

Practice (5 min)

Let's work on these questions:

  • Create a dictionary
  • Write an if / elif / else statement that checks a key and prints what it finds:
    • if the key is not in the dictionary, print that it's missing
    • elif the key's value is a list, print that it's a list
    • else the value is something other than a list, print that
Intro to Scientific Python

Practice (5 min), Walkthrough

Start with a dictionary and a key to look for:

my_dict = {"pet": "cat", "animals": ["cats", "dogs", "birds"]}
key = "pet"

Step 1: is the key missing?

if key not in my_dict:
    print(f"'{key}' is not in the dictionary")
Intro to Scientific Python

Practice (5 min), Walkthrough, cont.

Step 2: if it's there, is its value a list? elif checks next, and else catches the rest:

if key not in my_dict:
    print(f"'{key}' is not in the dictionary")
elif isinstance(my_dict[key], list):
    print(f"'{key}' is in the dictionary and its value is a list")
else:
    print(f"'{key}' is in the dictionary, but its value is not a list")

Try it with key = "color", "pet", and "animals".

Q: What happens if we check isinstance(my_dict[key], list) first?

Intro to Scientific Python

for Loops

Iterables are objects you can iterate over — lists, dictionaries, and more.

numbers = [1, 2, 3, 4, 5]

for number in numbers:
    print(number)
Intro to Scientific Python

for Loops, cont.

You can use a loop to build a new object from an existing one:

numbers_squared = []
for number in numbers:
    numbers_squared.append(number ** 2)
Intro to Scientific Python

Try it live

total = 0
for n in [1, 2, 3, 4, 5]:
    total = total + n

print(total)
Intro to Scientific Python

4. Built-in Functions

Intro to Scientific Python

Built-in Functions

Python ships with functions ready to use, no import needed.

Numerics: abs(), max(), min()

Boolean: any(), all(), bool()

Sequence-related: len(), input(), range()

Type constructors: dict(), float(), int(), list(), str(), set(), tuple()

Intro to Scientific Python

Try it live

len([1, 2, 3])
max(4, 7, 2)
min(4, 7, 2)
Intro to Scientific Python

Try it live, cont.

any([False, False, True])
all([True, True, False])
Intro to Scientific Python

All the Built-in Functions in Python

https://docs.python.org/3/library/functions.html

Intro to Scientific Python

🐍 Python Trick

Get information about a variable, built-in type, or function by adding a ? after it:

print?
Intro to Scientific Python

Practice (5 min)

Let's work on these questions:

Spend some time exploring the different built-in functions in Python.

Q: How is all() different from any()?

Q: What happens when you give a string to the list() function?

Q: What happens if you give a string to int()?

Intro to Scientific Python

5. Functions

Intro to Scientific Python

Defining a Function

Functions let you reuse a block of code. Defined with def, named in snake_case.

def print_hello_world():
    print("Hello world!")
Intro to Scientific Python

Functions with Arguments

def print_hello_person(person):
    print(f"Hello {person}!")

f"..." is an f-string — it lets you embed a variable directly inside a string.

Intro to Scientific Python

Returning a Value

print() shows something on screen; return lets you store the result for later use.

def greet(person):
    return f"Hello {person}!"
message = greet("Teon")
message
Intro to Scientific Python

Try it live

def greet(person):
    return f"Hello {person}!"

message = greet("Teon")
message
Intro to Scientific Python

Practice (15 min)

Let's work on these questions:

  1. Create a function that takes in a list and returns a dictionary where the keys are indexes.
  2. Create a function that takes a list, creates a reversed copy of it, and returns a list of tuples pairing both lists together.
  3. Create a function that prints three different messages based on the input type.
Intro to Scientific Python

6. Bringing it all together

Intro to Scientific Python

Bringing it all together

Combine everything from today: write a function that uses control flow and built-ins, run it in your notebook, then commit your work.

def classify_numbers(numbers):
    result = []
    for n in numbers:
        if n % 2 == 0:
            result.append("even")
        else:
            result.append("odd")
    return result
Intro to Scientific Python

Save Your Work

Check that you're on your personal branch (marked with a *), then commit:

cd ~/workspace/gsk-intro-scientific-python-course
git branch
git add notebooks/module_02.ipynb
git commit -m "Complete Module 02 exercises"
git log
Intro to Scientific Python

That's it for today!

Next class: Module 03 — Intro to NumPy.

Intro to Scientific Python

NOTE: the JupyterLite consoles/notebooks below point at the deployed GitHub Pages site (https://datalus-dev.github.io/gsk-intro-scientific-python-course/jupyterlite/), built and published automatically by .github/workflows/deploy-jupyterlite.yml on every push to main. To test against a local build instead, run `jupyter lite build --output-dir _build/jupyterlite --contents notebooks`, serve it, and swap the `src` host accordingly.