Reputation: 23
I want to prevent the user from entering an input other than + , - , / , * , and the code I've written works fine and it prevents user from entering numbers, strings, spaces, but when user presses the ENTER KEY the program skips the input question and goes to the next code block.
How can I prevent a user from pressing ENTER KEY and skipping the "Enter an Operator: " input question?
op_error = True
while op_error:
op_error = False
op = input("Enter an Operator: ")
if op in "+-/*":
break
elif len(op.strip()) == 0:
op_error = True
else:
op_error = True
Upvotes: 0
Views: 894
Reputation: 114300
The issue you are experiencing is with the test
if op in "+-/*":
Any string in the following list is going to pass, not just the empty string:
'', '+', '-', '/', '*', '+-', '-/', '/*', '+-/', '-/*', '+-/*'
The problem is that you are not checking if the string has length 1 before deciding if it is a valid operator. If you want to use only the in
operator you can do:
if op in ('+', '-', '/', '*'):
Notice that ''
and '+-'
will never be equal to an element of that tuple. Another way is to explicitly check for length:
if len(op) == 1 and op in '+-/*':
As an aside, there is no need for the op_error
variable in this case. It serves no logical purpose. Here is how you can rewrite the code in a much simpler way:
while True:
op = input("Enter an Operator: ")
if op in ('+', '-', '/', '*'):
break
The advantage of the tuple approach is that it allows you to have multi-character operators (e.g. python's **
). It will also make it much easier to transition to using a dictionary whose keys are the operators and whose values are, for example, processing hooks.
Upvotes: 3
Reputation: 1500
input
will return an empty string if only enter is press. You can test for it by comparing with '' (two single quotes) or "" (two double quotes) with no space between them.
op_error = True
while op_error :
op = input ('Enter an Operator: ')
if op != '' and op in '+-/*' :
op_error = False
print (op)
Upvotes: -1