I am trying to create a piece of code in Python 3 which allows the user to choose between several options. I have tried this several ways but none of them seem the right method to do so.
Example Attempt:
usr_input = input("Input: ")
while (usr_input != '1') | (usr_input != '2'):
if usr_input == '1':
search()
elif usr_input == '2':
sys.exit()
The problem with this is that the script hangs after entering an incorrect command.
Can anyone give me the correct way to do this?
There are a few things wrong here.
Firstly, you only get
usr_inputonce, outside the loop. If it’s not a correct choice, you don’t give the user the change to correct their choice: you simply loop. You’ll need to do theinputwithin the loop.Secondly, your boolean condition is wrong. It is the equivalent of saying “x is not a OR not b”, which is always true, since even if it is
ait is still notb. A better way of saying it isnot in ['1', '2'].Putting these together: