Hello! Today we will learn how to use the try-except statements. Here is a scheme of how try-except works:
try:
# This code tries to execute, but if there's an error, stop execution
except <err_name>:
# This code will get executed if the try block fails to execute
else: # Optional
# This code executes after the try block, only if try block doesn't return an error
finally: # Optional
# This code will always get executed
Also, you will need to replace with the error you want to catch. Ok, so let's see an example:
i = input()
try:
i = int(i)
print(f"Your number: {i}.")
except TypeError:
print("Your input isn't a number!")
finally:
print("Goodbye!")
if we input 6673 we will get:
Your number: 6673.
With that, Goodbye and have a nice day!
Top comments (0)