0
0
Pythonprogramming~10 mins

Why exceptions occur in Python - Test Your Understanding

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 [1] 0
except ZeroDivisionError:
    print("Cannot divide by zero")
Drag options to blanks, or click blank then click option'
A-
B+
C*
D/
Attempts:
3 left
💡 Hint
Common Mistakes
Using addition or multiplication instead of division.
2fill in blank
medium

Complete the code to convert a string to an integer safely.

Python
try:
    number = int([1])
except ValueError:
    print("Invalid number")
Drag options to blanks, or click blank then click option'
A"abc"
B123
CNone
D3.14
Attempts:
3 left
💡 Hint
Common Mistakes
Using a valid number string which does not cause an exception.
3fill in blank
hard

Fix the error in the code that causes a KeyError.

Python
data = {'name': 'Alice'}
print(data[[1]])
Drag options to blanks, or click blank then click option'
A'name'
B'phone'
C'address'
D'age'
Attempts:
3 left
💡 Hint
Common Mistakes
Using keys that are not in the dictionary causing KeyError.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that includes only words longer than 3 letters.

Python
words = ['cat', 'lion', 'dog', 'elephant']
lengths = {word: [1] for word in words if len(word) [2] 3}
Drag options to blanks, or click blank then click option'
Alen(word)
B>
C<
Dword
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong comparison operator or value.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that includes uppercase keys for words with length greater than 4.

Python
words = ['apple', 'bat', 'carrot', 'dog']
result = { [1]: [2] for word in words if len(word) [3] 4 }
Drag options to blanks, or click blank then click option'
Aword.upper()
Bword
C>
Dlen(word)
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up keys and values or using wrong comparison operators.