Module 2

Spring 2026

The following materials are meant to supplement the lectures and exercises for Module 2. They cover additional topics and examples related to Python Basics. Feel free to explore these resources to deepen your understanding of the concepts we are learning in class. If you have any questions or need further clarification on any of the topics, please don’t hesitate to ask!

Week 2

Jupyter Notebook is a web-based interface where you write and run Python code in interactive cells. It runs on a web browser and no local installation is required.

Creating a New Notebook

Here is the guide on how to create a new Jupyter notebook:

1. In the file browser, click **New** (top left).
2. Select **Python 3 (ipykernel)** from the dropdown. (Ask me if you are not sure which one to select)
3. A new notebook opens in a new browser tab.
Tip

You can also load an existing notebook by clicking File > Open (top left), clicking the Upload button (top right), and selecting the .ipynb file.

A Jupyter notebook is made up of two cells types:

Cell Type Purpose How to Run
Code cell Write and execute Python code Click the play button or press Shift + Enter
Markdown cell Write formatted notes and explanations Press Shift + Enter to render

When you run a code cell, the output appears directly below it.

Running Your First Cell

Click inside the first empty code cell and type:

# This is your first Jupyter cell
print("Hello, World!")

Press Shift + Enter. The output Hello, World! appears below the cell and a new cell is created automatically.

Useful Keyboard Shortcuts

Shortcut Action
Shift + Enter Run cell, move to next
Ctrl + Enter Run cell, stay in place
Ctrl + / Toggle comment
Esc Enter command mode
Enter Enter edit mode

Installing Extra Packages

To install a package from within a notebook cell, use pip with the ! prefix:

# The ! runs a shell command directly from the notebook
!pip install pandas

# Then import it normally in the next cell
import pandas as pd

Install Thonny IDE

Thonny is a lightweight Python IDE designed for beginners. It shows variable values, highlights errors clearly, and bundles its own Python interpreter, so setup is a single download.

Windows

1. Go to [thonny.org](https://thonny.org) and click the **Windows** download button.
2. Run the downloaded `.exe` installer and follow the prompts with default options.
3. Thonny installs Python 3 automatically if it is not already present.
4. Launch Thonny from the Start menu or desktop shortcut.

macOS

1. Go to [thonny.org](https://thonny.org) and click the **Mac** download button.
2. Open the downloaded `.pkg` file and follow the installer.
3. On first launch, macOS may ask you to confirm opening a downloaded app. Click **Open**.

Linux

Open a terminal and run:

# Using pip
pip3 install thonny
thonny

# Or using apt
sudo apt install thonny

Running Your First Script

Once the Thonny IDE is launched, click File > New to open a blank editor tab and type the following statements:

name = input("What is your name? ")  # asks the user to type something
print("Hello,", name)                # prints a greeting using their input

Click the green Run button and Thonny will prompt you to input your name and print the greeting message.

Tip

Save your files with .py extensions and descriptive names like week2_exercise.py rather than untitled.py.

Week 3

Variables are named storage locations in Python that hold values. When you write x = 42, Python creates a variable called x and assigns it the integer value 42. Python is duck typed 🐣, which means a variable’s type is determined by its value. The variable’s type can change if you reassign it.

x = 42          # int
x = "hello"     # now a str, and Python allows this! 🐣
score = 95.5    # float
passed = True   # bool
grades = [88, 92, 75]  # list

Use assert to check that your variables hold expected values during development as they raise an AssertionError if the condition is False:

assert x > 0
assert name != ""
assert score <= 100

Data Types

Python has four primitive (built-in) data types you will use constantly. The type() function tells you what type a value is at any moment.

Type Keyword Example type() result
Integer int 42 <class 'int'>
Floating-point float 3.14 <class 'float'>
String str "hello" <class 'str'>
Boolean bool True <class 'bool'>
x = 42
print(type(x))        # <class 'int'>

pi = 3.14159
print(type(pi))       # <class 'float'>

name = "Alice"
print(type(name))     # <class 'str'>

passed = True
print(type(passed))   # <class 'bool'>

Type Conversion

You can convert between types using the built-in conversion functions; however, be aware of edge cases as some conversions raise errors.

# int() converts strings of digits and truncates floats
int("42")       # 42  — string to int works fine
int(3.99)       # 3   — decimal part is dropped, not rounded
# int("hello") — raises ValueError, non-numeric string

# float() widens an int or converts a numeric string
float(7)        # 7.0
float("2.5")    # 2.5

# str() turns almost anything into a string
str(100)        # "100"
str(3.14)       # "3.14"
str(True)       # "True"

# bool() follows Python's truthiness rules
bool(1)         # True  — any non-zero number is truthy
bool(0)         # False — zero is falsy
bool("hi")      # True  — non-empty string is truthy
bool("")        # False — empty string is falsy
bool(None)      # False

Multiple Assignment

Python lets you assign several variables in one line. This keeps code concise and is especially useful when swapping values.

# Assign different values to multiple variables at once
a, b = 1, 2
print(a, b)     # 1 2

# Swap without a temporary variable
a, b = b, a
print(a, b)     # 2 1

# Assign the same value to many variables at once
x = y = z = 0
print(x, y, z)  # 0 0 0

# Unpack a list directly into named variables
first, second, third = [10, 20, 30]

Naming Conventions

Choosing clear and consistent names makes code readable for you and for anyone else who reads it. Python has a few official guidelines from PEP 8. A valid Python name must:

  • Start with a letter or underscore (_), never a digit
  • Contain only letters, digits, and underscores
  • Not be a reserved keyword such as for, if, return, or class
Rule Style Example
Regular variables and functions snake_case (all lowercase, underscores) student_grade, total_score
Constants UPPER_CASE MAX_STUDENTS, PI
Classes PascalCase StudentRecord
Private leading underscore _helper
# Good names
student_age = 20       # snake_case, descriptive
MAX_RETRIES = 3        # UPPER_CASE constant

# Names that cause errors
# 2fast = True        # starts with a digit — SyntaxError
# my-var = 5          # hyphen is not allowed — SyntaxError
# for = 10            # reserved keyword — SyntaxError

Week 4

A for loop in Python repeats a block of code a fixed number of times, iterating over a sequence. The range() function is the most common way to generate that sequence, and it accepts up to three arguments: start, stop, and step.

# 0, 1, 2, 3, 4
for i in range(5):        
    print(i)
# 2, 4, 6, 8
for i in range(2, 10, 2): 
    print(i)

Explaination

range() generates a sequence of integers without storing them all in memory at once. It comes in three forms:

Form Meaning Example values
range(n) 0 up to (not including) n range(4) gives 0, 1, 2, 3
range(start, stop) start up to (not including) stop range(2, 6) gives 2, 3, 4, 5
range(start, stop, step) Every step-th value range(0, 10, 2) gives 0, 2, 4, 6, 8

A negative step counts backwards. The loop ends when the value reaches or passes stop.

# Basic range: 0, 1, 2, 3, 4
for i in range(5):
    print(i)

# Custom start and stop: 10, 11, 12, 13, 14
for i in range(10, 15):
    print(i)

# Step by 3: 0, 3, 6, 9
for i in range(0, 12, 3):
    print(i)

# Negative step (countdown): 5, 4, 3, 2, 1
for i in range(5, 0, -1):
    print(i)

Loop Over A List

When you loop over a list with a plain for loop, you get the values but not the position. enumerate() gives you both the index and the value together, which is cleaner than maintaining a separate counter variable.

animals = ["cat", "dog", "bird"]

# Without enumerate (manual counter)
i = 0
for animal in animals:
    print(i, animal)
    i += 1

# With enumerate (cleaner, less error-prone)
for i, animal in enumerate(animals):
    print(i, animal)
# 0 cat
# 1 dog
# 2 bird

# Start the index at 1 instead of 0
for i, animal in enumerate(animals, start=1):
    print(f"{i}. {animal}")
# 1. cat
# 2. dog
# 3. bird

Skip The Loop

break exits the loop immediately and skipping any remaining iterations. continue skips the rest of the current iteration but not exit.

# break: stop as soon as the target is found
numbers = [3, 7, 2, 9, 4]
for n in numbers:
    if n == 2:
        print("found 2, stopping")
        break           # loop ends here; 9 and 4 are never visited
    print(n)
# Prints: 3, 7, found 2 stopping

# continue: skip certain values but keep looping
for n in range(10):
    if n % 2 == 0:
        continue        # skip even numbers
    print(n)            # only odd numbers reach this line
# Prints: 1, 3, 5, 7, 9

Nested For Loops

A nested for loop is a loop placed inside another loop. The inner loop runs completely for every single iteration of the outer loop. This is commonly used when working with two-dimensional structures like a list of lists (e.g. a table or grid).

# A 2D list (3 rows, each with 3 values)
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

for row in matrix:          # outer loop: each row
    for value in row:       # inner loop: each item in that row
        print(value, end=" ")
    print()                 # newline after each row
# 1 2 3
# 4 5 6
# 7 8 9

Keep in mind that each extra level of nesting multiplies the number of operations. Two nested loops over lists of length n perform roughly n * n iterations. For large datasets, this can become slow, so prefer built-in functions or list comprehensions when possible.

Decimal to Binary Conversion

Python provides built-in functions to convert between number bases:

bin(42)           # '0b101010'   decimal to binary string
hex(255)          # '0xff'       decimal to hex string
int("101010", 2)  # 42           binary string to decimal
int("ff", 16)     # 255          hex string to decimal

Bitwise Operators

Bitwise operators work directly on the individual bits of integers:

Operator Name Example Result
& AND 42 & 27 10
| OR 42 | 27 59
^ XOR 42 ^ 27 49
a = 42   # 0b00101010
b = 27   # 0b00011011
# Using the Bitwise Operators
a & b    # 0b00001010 (10) (both bits must be 1)
a | b    # 0b00111011 (59) (either bit is 1)
a ^ b    # 0b00110001 (49) (exactly one bit is 1)

Bit Shifting

Left-shifting by n is equivalent to multiplying by 2^n. Right-shifting by n is equivalent to floor-dividing by 2^n. Shifting moves all bits left or right by a given number of positions:

13 << 1   # 26   (multiply by 2^1)
13 << 2   # 52   (multiply by 2^2)
13 >> 1   # 6    (integer divide by 2^1)
13 >> 2   # 3    (integer divide by 2^2)