0
0
Pythonprogramming~10 mins

Try–except–else behavior 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 ZeroDivisionError exception.

Python
try:
    result = 10 / 0
except [1]:
    print("Cannot divide by zero")
Drag options to blanks, or click blank then click option'
AValueError
BIndexError
CZeroDivisionError
DTypeError
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong exception type like ValueError or TypeError.
Not catching any exception.
2fill in blank
medium

Complete the code to print 'Success' only if no exception occurs.

Python
try:
    x = 5 / 1
except ZeroDivisionError:
    print("Error")
else:
    print([1])
Drag options to blanks, or click blank then click option'
A"Failed"
B"Done"
C"Error"
D"Success"
Attempts:
3 left
💡 Hint
Common Mistakes
Putting the success message inside except block.
Not using quotes around the string.
3fill in blank
hard

Fix the error in the code to correctly handle exceptions and print 'No error' if none occur.

Python
try:
    value = int('abc')
except ValueError:
    print("Conversion failed")
else:
    print([1])
Drag options to blanks, or click blank then click option'
A"No error"
BNo error
CNoError
Dno error
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting quotes around the string in print.
Using undefined variable names.
4fill in blank
hard

Fill both blanks to create a try-except-else that prints the square root if no error occurs and prints 'Error' if a ValueError happens.

Python
import math

try:
    num = int(input('Enter a number: '))
    result = math.sqrt(num)
except [1]:
    print('Error')
else:
    print([2])
Drag options to blanks, or click blank then click option'
AValueError
BTypeError
Cresult
Dnum
Attempts:
3 left
💡 Hint
Common Mistakes
Catching the wrong exception type.
Printing the input number instead of the result.
5fill in blank
hard

Fill all three blanks to create a try-except-else that divides two numbers, catches ZeroDivisionError, and prints the quotient if no error.

Python
try:
    numerator = 10
    denominator = 2
    quotient = numerator [1] denominator
except [2]:
    print('Cannot divide by zero')
else:
    print([3])
Drag options to blanks, or click blank then click option'
A/
BZeroDivisionError
Cquotient
D*
Attempts:
3 left
💡 Hint
Common Mistakes
Using multiplication instead of division.
Catching the wrong exception.
Printing the wrong variable.