Programming with Python
Kühne Logistics University Hamburg - Fall 2024
keys()
, values()
Tip
Comprehensions for concise creation of these structures are often used in practice to create new data structures from existing ones.
open()
with
statement for safer file handlingNote
This covers the main points from our last lecture on data structures and file handling in Python.
ZeroDivisionError: division by zero
Warning
Undiscovered errors can be very hard to debug and can cause crashes and other issues.
ValueError
: argument of correct type but inappropriate valueTypeError
: function applied to object of inappropriate typeNameError
: raised when a local or global name is not foundIndexError
: raised when a sequence subscript is out of rangeKeyError
: raised when a dictionary key is not foundFileNotFoundError
: file or directory not foundZeroDivisionError
: division or modulo by zeroAttributeError
: attribute reference or assignment failsImportError
: import of a modulefailsSyntaxError
: parser encounters a syntax errorIndentationError
: indentation is not correctRuntimeError
: error does not fall into any categoryNote
The list of built-in exceptions is even longer, these are just the most common ones. We won’t cover the errors listed here in detail, but it is good to be aware of them.
try-except
blocks are used to handle exceptionstry
block contains the code that might raise an exceptionexcept
block contains the executed code if an exception occursError: Division by zero is not allowed.
I will be printed as the exception was handled!
try:
# Code that might raise an exception
# ...
except ExceptionType as e:
# Code to handle the specific exception type
# ...
except Exception as e:
# Code to handle any other exceptions
# ...
Note
as e
is used to store the exception in a variable. Not mandatory, but good practice to do so.
>Grouptask: Solve the following problem using try-except blocks:
# Implement a function that converts a string to an integer
# 1. Try to convert the input_string to an integer
# 2. If successful, return the integer
# 3. If a ValueError occurs, catch it and return "Invalid input: not a number"
# 4. If any other exception occurs, catch it and return
# "An unexpected error occurred: [type of exception]"
# Your code here
# Test cases
print(string_to_int("42")) # Should print: 42
print(string_to_int("Hello")) # Should print: Invalid
print(string_to_int([123]))
Question: What is the output of the last line?
raise
statement>Question: What do you think the raise
statement will show now?
class InvalidUsernameError(Exception):
pass
def get_valid_username():
while True:
try:
username = input("Please enter a username (no spaces): ")
if " " in username:
raise InvalidUsernameError("Username must not contain spaces.")
return username
except InvalidUsernameError as e:
print(f"Invalid username: {e}")
print("Please try again.")
AssertionError
is raised>Task: Try to run the code above and discuss what happens.
Note
isinstance
is a built-in function that checks if an object is an instance of a class.
>Grouptask: Solve the following problem using assertions:
# Implement a function that takes a list of integers and returns the sum of the numbers.
# 1. Use assertions to check if the input is a list
# 2. Use assertions to check if the list contains only integers.
# 3. If the list contains only integers, return the sum of the numbers
# Your code here
# Test cases
print(sum_of_numbers([1, 2, 3, 4, 5])) # Should print: 15
print(sum_of_numbers([1, 2.0, 3, 4, 5])) # Should print: AssertionError
print
and assert
statements to debug our codeprint
: check the values of variables at different pointsassert
: check calculations or the types of variablesHello
42.0
Note
While this can be useful, it is not always the best way to debug code.
>Task: Open Thonny and copy the following code:
def calculate_average(numbers):
total = 0
count = 0
for num in numbers:
total += num
count += 1
average = total / count
return average
# Test cases
test_lists = [
[1, 2, 3, 4, 5],
[10, 20, 30],
[]
]
for i, test_list in enumerate(test_lists):
print(f"Test case {i + 1}:")
result = calculate_average(test_list)
print(f"Average: {result}\n")
>Task: Run the code and use the debugging tools to find the error.
>Question: What do you think the error is?
Note
The enumerate
function used in the code is super helpful function that returns a tuple containing the index and the value of the item in the list and it is not the error.
Note
And that’s it for todays lecture!
We now have covered the basics of errors, exceptions and debugging in Python. Logging is beyond our scope, but it is good to know should you work with larger codebases later on.
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 V - Handling Errors | Dr. Tobias Vlćek | Home