The except
-part of try-except only run if what's inside the try
-part throws an error.
An example is divisibility by zero. The following code will throw an error when trying to run it in the python shell;
print(5/0)
You can catch this error, and print your own message instead of the python shell printing its own. In this case ZeroDivisionError
is the certain type of error python will throw. With the following code, python will just catch that error, and not any other.
try:
print(5/0)
except ZeroDivisionError:
print("Cannot divide by zero")
If you want to catch all errors, you simply just write except
instead of except zeroDivisionError
.
The code inside the except
-block don't run because there is no error when trying to run what's inside the try
-block. What is happening inside the try-block is simply assigning an input to a variable. There is no error throwed for this line, and thus the except
-block don't run.
There are different ways to get the functionality you want. You probably want to repeat that the input needs to be a string, until the user actually enters a string. You can do just that with a while
-loop. The specific error that is thrown if string to integer conversion fails is ValueError
.
isString = False
while not isString:
userInput = input("Enter here: ")
try:
int(userInput)
except ValueError:
# if string to integer fails, the input is a string
isString = True
else:
print("Please enter a string")
The while loop above runs as long as isString
is False
. First we try to convert from string to integer. If this throws an error, the input is a string, therefore we're setting the isString to True
, and the while-loop will not run anymore. If the conversion is sucessfull, it implies that the input is actually an integer, and thus the else-statement will run, printing that the user needs to enter a string.