Reputation: 11
Alright, so I've got a try and except block watching out for exceptions. This is all normal but when you've got a loop you can't stop the code usually, as there's no specific bit saying "Don't catch KeyboardInterrupt errors" or something alike
Is there anything that let's try and except blocks exclude specific errors? (or an alternative)
My code
while 1:
if ques == 'n':
try:
newweight = int(input('Please enter a number'))
exit()
except:
print('Please enter a valid number')
Now this will create an infinite loop as the "exit()" will not happen as it will get raised an as exception, and it will thus create an infinite loop. Is there any way for this to not happen?
Upvotes: 0
Views: 54
Reputation: 125
To prevent a user entering a non-integer value, you want to catch a TypeError so you can change except:
to except ValueError:
and it will then catch any invalid inputs. That should cover you sufficiently.
Upvotes: 3