You will have noticed that when something goes wrong in a Python program you see an error message. This is called an exception, and you can handle them explicitly to prevent your program from aborting and printing an unhelpful traceback.
For example, take the following code that asks the user to enter an integer, then prints "Hello" that number of times:
In [1]:
n = int(input("Enter an integer: "))
print("Hello " * n)
This failed when we provided input that could not be converted to an integer.
We can re-write this so that we catch the exception before it gets to the user, and print a helpful message instead:
In [2]:
try:
n = int(input("Enter an integer: "))
print("Hello " * n)
except ValueError:
print("That wasn't an integer!")
You can handle errors in anyway that might be appropriate for your program.
We could take this one step further by continually asking the user for input until we get an integer:
In [3]:
while True:
try:
n = int(input("Enter an integer: "))
print("Hello " * n)
break
except ValueError:
print("That wasn't an integer! Try again...")
except KeyboardInterrupt:
print('bye')
break