Recover From Errors (Solution)
This is going to be a string so far, right? But I do want it to be an integer. So what I can generally do is I can convert this to an integer, so I’m going to say
int(), use the
int() function here to convert this to an integer.
I enter an integer, so if I enter an integer here,
3, then no problem. But let’s try it again. If I enter something that can’t be converted to an integer, like
e, then I get this traceback
ValueError because Python can’t convert the
e to an integer.
I’m going to say try to convert the user’s input to an integer, and then I want to print it,
users_integer. And now I’m going say
except I run into this
ValueError, and then I want to do this again, right? So I want to collect another input.
But now I still need to get out of this infinite loop somehow. So, for this, you can use the
break keyword that you’ve practiced before, and we put it into the condition where you actually achieved what you want to achieve, right?
So in this case, I’m going to say
break if we did not run into a
ValueError, if it worked successfully to convert the user’s input to an integer and then print it back out to them, then we’re done with the program. Then I want to break out of this infinite loop.
And here’s that solution:
while True, try to collect the user input and print it out. In this case, you’re doing the integer conversion, not right on the input, but then afterwards, which comes down to the same because it’s both still in the same part of the
except block. So, it’ll still throw the
ValueError and then catch it down here, and otherwise the solution is the same.
Become a Member to join the conversation.