Python EXCEPTIONS Exercise for Beginners and Intermediate

Enable the edit mode with double click on the editor.
For answers, please select the invisible text right after Answer:


Add the necessary clause(s) to the code below so that in case the ZeroDivisionError exception is raised, then the program prints out Zero! to the screen.

try:
    print(25 % 0)
Zero!

Answer:

try:
    print(25 % 0)
except ZeroDivisionError:
    print("Zero!")

Add the necessary clause(s) to the code below so that in case the code under try raises no exceptions then the program prints out the result of the math operation and the string Clean! to the screen.

try:
    print(25 % 5 ** 5 + 5)
except:
    print("Bug!")
30
Clean!

Answer:

try:
    print(25 % 5 ** 5 + 5)
except:
    print("Bug!")
else:
    print("Clean!")

Add the necessary clause(s) to the code below so that no matter if the code under try raises any exceptions or not, then the program prints out the string Result! to the screen.

try:
    print(25 % 5 ** 5 + 5)
except:
    print("Bug!")
Bug!
Result!

Answer:

try:
    print(25 % 5 ** 5 + 5)
except:
    print("Bug!")
finally:
    print("Result!")

Add the necessary clause(s) to the code below so that in case the code under try raises the ZeroDivisionError exception then the program prints out the string Zero! to the screen; additionally, if the code under try raises the IndexError exception then the program prints out the string Index! to the screen.

x = [1, 9, 17, 32]
try:
    print(x[3] % 3 ** 5 + x[4])
Index!

Answer:

x = [1, 9, 17, 32]
try:
    print(x[3] % 3 ** 5 + x[4])
except ZeroDivisionError:
    print("Zero!")
except IndexError:
    print("Index!")

Add the necessary clause(s) to the code below so that in case the code under try raises no exceptions then the program prints out the result of the math operation and the string Clean! to the screen. If the code under try raises the ZeroDivisionError exception then the program prints Zero! to the screen. Ultimately, regardless of the result generated by the code under try, the program should print out Finish! to the screen.

try:
    print(25 % 5 ** 5 + 5)
30
Clean!
Finish!

Answer:

try:
    print(25 % 5 ** 5 + 5)
except ZeroDivisionError:
    print("Zero!")
else:
    print("Clean!")
finally:
    print("Finish!")

Leave a Reply

Prev
Python LOOPS Exercise for Beginners and Intermediate

Python LOOPS Exercise for Beginners and Intermediate

Enable the edit mode with double click on the editor

Next
Python FUNCTIONS Exercise for Beginners and Intermediate

Python FUNCTIONS Exercise for Beginners and Intermediate

Enable the edit mode with double click on the editor

You May Also Like