Programming with Python
Kühne Logistics University Hamburg - Fall 2024
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
statementNote
The 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
statementsTip
That’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!
Tip
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.53981633974483
Tip
Note, 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 b
random.randint(a, b)
: random integer between a
and b
random.choice(list)
: random element from a listrandom.shuffle(list)
: shuffle a listTip
There 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:
Tip
Remember, 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 directoryTip
These 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 row
Task: 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 here
re
module to work with regular expressions<re.Match object; span=(7, 12), match='World'>
Note
So far, we could also have achieved this with the find
method of a string.
7
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 patternNote
As always, there is more. But these are a good foundation to build upon.
Task: Replace all occurences of Python
by “SECRET”.
Note
Regular expressions are even more powerful when combined with special characters.
.
matches any character*
matches zero or more of the preceding element+
matches one or more of the preceding element?
matches zero or one of the preceding element[]
matches any character in the brackets|
matches either the left or the right side\d
matches any digit\w
matches any word character (alphanumeric and underscore)\s
matches any whitespace character['123-45-6789']
Tip
It can be quite complicated to get the hang of these special characters, especially at the beginning. Gladly, there are tools like regexr.com that can help with building the right pattern. Apart from that, help(re)
in the terminal can also be very helpful.
Task: Use regular expressions to extract all dates from the text.
pip install <package_name>
to install a specific packageTip
With Thonny you can install packages directly in the IDE. Simply click on Tools -> Manage packages and search for the package you want to install.
Task: Install the pandas
and numpy
packages, which are commonly used for data analysis. We will use them together next week!
Tip
If you install packages like this, you can use the shell to do so! Alternatively, you can use pip install <package_name>
in the Python terminal or Thonny.
venv
moduleNote
And that’s it for todays 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.
Tip
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