Programming with Python
Kühne Logistics University Hamburg - Fall 2025
ValueError, TypeError, etc.>ValueError: invalid literal for int() with base 10: ‘Hello, World!’
try-except blocks are used to handle exceptionstry block contains code that might raise an exceptionexcept block contains code executed if an exception occursraise statementThe type if raised exception has to exist or you have to create a custom error type before.
AssertionError is raisedQuestion: Will this raise an AssertionError?
print and assert statementsThat’s why IDEs are so helpful in coding.
.py files containing Python codeHello from my_function!
Hello from another_function!
Hello from yet_another_function!
This is a good way to avoid importing too much from a module. In addition, we don’t need to use the module name before the function name when we use the functions from the module.
Python comes with many built-in modules. Common ones include:
| Module | Description |
|---|---|
math |
Different mathematical functions |
random |
Random number generation |
datetime |
Date and time manipulation |
os |
Operating system interaction |
csv |
Reading and writing CSV files |
re |
Regular expression operations |
Task: Use Python’s math module to calculate the area of a circle.
# Import the `math` module.
# Define a function named `calculate_area` that takes the radius `r` as an argument.
# Inside the function, use the `math.pi` constant to get the value of π.
# Calculate the area in the function and return it.
# Your code here
assert calculate_area(5) == 78.53981633974483Note, how assertations can be used to check if a function works correctly.
The random module provides functions for random numbers
random.random(): random float between 0 and 1random.uniform(a, b): random float between a and brandom.randint(a, b): random integer between a and brandom.choice(list): random element from a listrandom.shuffle(list): shuffle a listThere are many more functions in the random module. Use the help() function to get more information about a module or function.
Task: Time for a task! Import the random module and create a small number guessing game with the following requirements:
# TODO: Implement a random number guessing game.
# The game should work as follows:
# - The computer selects a random number between 1 and 10
# - The user has to guess the number and has three guesses
# - The computer tells the user whether their guess is too high, too low, or correct
# - The computer should also print how many guesses the user made before guessing the number correctly
# - It should also ask the user if they want to play again
# Your code hereRemember, that the input function always returns a string!
os module provides functions to interact with the OSos.listdir(path): list all files and directories in a directoryos.path.isfile(path): check if a path is a fileos.path.exists(path): check if a path existsos.makedirs(path): create a directoryThese can be quite useful for file handling. The os module contains many more functions, e.g. for changing the current working directory, for renaming and moving files, etc.
csv.writer(file)csv.reader(file)import csv # Import the csv module
with open('secret_message.csv', 'w') as file: # Open the file in write mode
writer = csv.writer(file) # Create a writer object
writer.writerow(['Entry', 'Message']) # Write the header
writer.writerow(['1', 'Do not open the file']) # Write the first row
writer.writerow(['2', 'This is a secret message']) # Write the second rowTask: Copy the code and run it. Do you have a new file?
Task: Time for another task! Do the following:
# First, check if a directory called `module_directory` exists.
# If it does not, create it.
# Then, list all files in the current directory and save them in a CSV file called `current_files.csv` in the new `module_directory`.
import os
if not os.path.exists('module_directory'):
pass
# Your code hereLet’s see the limitations of basic string methods:
Regular expressions solve these problems by finding patterns! Let’s work with this sample text throughout our examples:
re.search(pat, str): search for a pattern in a stringre.findall(pat, str): find all occurrences of a patternre.fullmatch(pat, str): check if entire string matches patternre.sub(pat, repl, str): replace a pattern in a stringre.split(pat, str): split a string by a patternAs always, there is more. But these are a good foundation to build upon.
Found 'User': ['User', 'User', 'User']
Task: Find all occurrences of “logged” in the sample text.
The . matches any single character:
sample_text = """
User john123 logged in at 2024-01-15
User mary_doe logged in at 2024-01-16
User bob logged in at 2024-01-17
Error: user invalid_user! failed login
"""
# Find "User" followed by any character, then "o"
result = re.findall(r'bo.', sample_text)
print(f"Found 'bo.': {result}") # This finds "bob"Found 'bo.': ['bob']
Task: Use . to find all 4-letter words starting with “use”.
The dot is like a wildcard - it fills in for any single character you don’t know.
[abc]Square brackets match any character inside them:
Users starting with j or m: ['User john123', 'User mary_doe']
Useful character classes:
[abc] - matches a, b, or c[a-z] - matches any lowercase letter[0-9] - matches any digit[a-zA-Z0-9] - matches letters and numbersTask: Find all years.
Instead of writing [0-9], we can use shortcuts:
| Shortcut | Meaning | Same as |
|---|---|---|
\d |
Any digit | [0-9] |
\w |
Word character | [a-zA-Z0-9_] |
\s |
Whitespace | [ \t\n] |
Found dates: ['2024-01-15', '2024-01-16', '2024-01-17']
Task: Find all usernames using \w.
Instead of repeating \d\d\d\d, we can specify quantities:
| Quantifier | Meaning |
|---|---|
{4} |
Exactly 4 times |
{2,4} |
Between 2 and 4 times |
+ |
One or more times |
* |
Zero or more times |
? |
Zero or one time |
Dates with quantifiers: ['2024-01-15', '2024-01-16', '2024-01-17']
Task: Find usernames of any length with \w+.
Let’s build an email pattern step by step!
Basic emails: ['john@email.com', 'doe@company.org', 'bob@test.co']
Better emails: ['john@email.com', 'mary.doe@company.org', 'bob@test.co']
When your regex doesn’t work:
Remember: regex can be complex, but you don’t need to master everything at once. Start simple and build up!
Task: Replace all occurences of Python by “SECRET”.
Task: Use regular expressions to extract all dates from the text.
uv add <package_name> to install a specific packageTask: Install the pandas and numpy packages, which are commonly used for data analysis. We will use them together next week!
If you install packages like this, you can use the shell to do so! Alternatively, you can use uv add <package_name> in the terminal in the IDE.
Common uv command you’ll use:
And that’s it for today’s lecture! We now have completed the first step into data science in Python. Next week, we can use this new knowledge to start to work with some tabular data and matrices.
Nothing new here, but these are still great books!
For more interesting literature to learn more about Python, take a look at the literature list of this course.
Lecture VI - Using Modules and Packages | Dr. Tobias Vlćek | Home