0
0
Pythonprogramming~10 mins

Common exception types in Python - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to catch a division by zero error.

Python
try:
    result = 10 / 0
except [1]:
    print("Cannot divide by zero!")
Drag options to blanks, or click blank then click option'
AValueError
BZeroDivisionError
CTypeError
DIndexError
Attempts:
3 left
💡 Hint
Common Mistakes
Using ValueError instead of ZeroDivisionError.
Using TypeError which is for wrong data types.
2fill in blank
medium

Complete the code to catch an error when accessing a list index that does not exist.

Python
my_list = [1, 2, 3]
try:
    print(my_list[5])
except [1]:
    print("Index out of range!")
Drag options to blanks, or click blank then click option'
AKeyError
BValueError
CAttributeError
DIndexError
Attempts:
3 left
💡 Hint
Common Mistakes
Using KeyError which is for dictionary keys.
Using AttributeError which is for missing object attributes.
3fill in blank
hard

Fix the error in the code by catching the correct exception type when converting a string to an integer.

Python
user_input = "abc"
try:
    number = int(user_input)
except [1]:
    print("Invalid number!")
Drag options to blanks, or click blank then click option'
AValueError
BTypeError
CNameError
DZeroDivisionError
Attempts:
3 left
💡 Hint
Common Mistakes
Using TypeError which is for wrong data types, not invalid values.
Using ZeroDivisionError which is unrelated.
4fill in blank
hard

Fill both blanks to catch errors when opening a file that does not exist and when reading from it.

Python
try:
    with open('missing.txt', '[1]') as file:
        content = file.read()
except [2]:
    print("File error occurred.")
Drag options to blanks, or click blank then click option'
Ar
Bw
CFileNotFoundError
DIOError
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w' mode which creates a file instead of reading.
Catching IOError instead of FileNotFoundError.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that includes only keys with string values longer than 3 characters.

Python
data = {'a': 'cat', 'b': 'elephant', 'c': 42}
result = {k: v for k, v in data.items() if isinstance(v, [1]) and len(v) [2] [3]
Drag options to blanks, or click blank then click option'
Astr
B>
C3
Dint
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'int' instead of 'str' for type check.
Using '<' instead of '>' for length comparison.