Use the else block
Write a Python program that uses else to run code only when no exception occurred.
"25", "x"
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)25 squared is 625 x is not a number
Line by line
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.