Reputation:
I have a hopefully simple question that I can't seem to find an answer to.
In the following code, I am creating an input validation feature to make sure the user inputs any of four valid "operations" (A.K.A the single letters 'a', 's', 'm', or 'd' and nothing else), so, I'm checking if the "operation" the user inputs is NOT equal to the any of the strings 'a', 's', 'm', or 'd'. If the condition is met, an error message will be printed and the program will be restarted as the code (mostly) shows.
print("Select an operation:")
print("Add (a)"), print("Sub (s)")
print("Mul (m)"), print("Div (d)")
operation = input()
if "a" not in operation:
print("Invalid operation.")
continue
Please tell me a way I can check if the operation matches ANY of the four letters. And, just to clear up, I don't mean that I need to OR (the logic function) 'a', 's', 'm', and 'd'.
All correspondence and help is much appreciated, thanks! :)
Upvotes: 0
Views: 40
Reputation: 114048
ummm perhaps
operation = input()
assert operation in ('a', 's', 'm', 'd'), "Error you must use one of 'a', 's', 'm', or 'd'"
I guess
basically you want to check that your operation in list of options
of coarse if your list of options is huge, then using a set is much more appropriate ... or a dictionary that provides a mapping from operations to methods ie
operations = {
"a":add,
"s":sub,
"m":mul,
"d":div
} #these are methods defined elsewhere
operation = input()
if operation in operations:
operations[operation]() #call the method
Upvotes: 0
Reputation:
You can use the not in
operator with a tuple of values to test for:
if operation not in ('a', 's', 'm', 'd'):
The condition of the above if-statement will evaluate to True
if operation
does not equal any of the values in the tuple ('a', 's', 'm', 'd')
.
Note too that you are using continue
incorrectly: it may only be used inside a loop.
If you want to loop until the user enters a proper value, you can use something like this:
while True: # Loop continuously
operation = input("Enter a value: ") # Get the input
if operation in ('a', 's', 'm', 'd'): # See if it can be found in the tuple
break # If so, break the loop
Upvotes: 2
Reputation: 17510
You probably want something like:
allowed_operations = set(('a', 's', 'm', 'd'))
while True:
operation = input() # raw_input() for Python earlier than 3
if operation not in allowed_operations:
print ('Error: Must choose one of a, s, m, d\nPlease try again')
else:
break
Upvotes: 0