I have a variable 'action' which I want to input from the user and validate, I have a while loop and a try-except block to catch the values which raise an error or are invalid according to the functionality of the rest of the code
while True: # Input and validation of 'action'
try:
action = int(input('Please enter what you would like to do: '))
if action < 0:
negativeError = ValueError('This value is negative')
raise negativeError
if action != 1 or action != 6:
invalidValueError = ValueError('Not a valid option')
raise invalidValueError
break
except:
ValueError or TypeError
print('That is invalid, please enter a valid number corresponding to one of the actions above')
continue
If I input for example 1 on the first iteration, it breaks out of the loop as expected, but if I input -5 (which except catches) on the first iteration THEN input 1 in the second iteration it catches it as if 1 is an invalid value and does not break out of the loop and keeps iterating. I am new to error handling so any help would be appreciated.
CodePudding user response:
I think it should look like this:
while True: # Input and validation of 'action'
try:
action = int(input('Please enter what you would like to do: '))
if action < 0:
negativeError = ValueError('This value is negative')
raise negativeError
if action not in [1, 6]:
invalidValueError = ValueError('Not a valid option')
raise invalidValueError
break
except ValueError or TypeError:
print('That is invalid, please enter a valid number corresponding to one of the actions above')
continue
action != 1 or action != 6 is always true.
CodePudding user response:
- Your if statement is not correct.
- Print the message generated during the except raising instead of creating a new message.
while True: # Input and validation of 'action'
try:
action = int(input('Please enter what you would like to do: '))
if action < 0:
negativeError = ValueError('This value is negative')
raise negativeError
if not (action == 1 or action == 6):
invalidValueError = ValueError('Not a valid option')
raise invalidValueError
break
except (ValueError,TypeError ) as e:
print(e)
CodePudding user response:
Try something like this. We'll use a default parameter value for now. This can be modified later (i.e., passed by the caller) thus obviating the need to modify this code:
def get_action(valid_actions=[1,6]):
action_list = ','.join(map(str, valid_actions))
while True:
try:
input_ = input(f'Please select an action from this list {action_list}: ')
response = int(input_)
if response in valid_actions:
return response
raise ValueError
except ValueError:
print('Invalid response. Try again')
get_action()
Subsequently you might want to add another action - say 3. In which case:
get_action([1,3,6])
...is all that you'd need