Python Practice › Exception Handling Programs › Program 7
Use the else block
Write a Python program that uses else to run code only when no exception occurred.
Input
"25", "x"
Output
25 squared is 625 x is not a number
Approach
elseruns aftertryonly if nothing was raised.
Solution
for text in ["25", "x"]: try: n = int(text) except ValueError: print(text, "is not a number") else: print(text, "squared is", n * n)Output
25 squared is 625 x is not a number
Line by line
Lines 6-7
Keeping the follow-up work in else means a bug there is not hidden by the except.
Learn the concept
New to this topic? Read the lesson, then come back.