Is there a way to test if an expression leads to an error
without running it normally (which would lead to a program crash)?
In particular, the chunk int(temp[1])
without knowing whether or not temp[1]
is a number (as in a string number such as "10" or "142")? The reason I'm trying to do this is to implement error handling involving in regards to user input.
CodePudding user response:
You can use type(temp[1])
or isinstance(temp[1], int)
to check types. To specifically check if strings are numbers, use temp[1].isdigit()
.
CodePudding user response:
You could try if isinstance(temp[1], int)
. This checks if temp[1]
is an instance of the int
class.
Another way to do this is to catch the error itself. That way you know for a fact that it causes the error. For example:
try:
int(temp[1])
except ValueError:
print("The variable temp[1] can't be changed to an int.")