Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

Python 3: Creating A Function For User Choice

Writer Andrew Henderson

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?

1

3 Answers

There are a few things wrong here.

Firstly, you only get usr_input once, 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 the input within 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 a it is still not b. A better way of saying it is not in ['1', '2'].

Putting these together:

usr_input = ''
while usr_input not in ['1', '2']: usr_input = input("Input: ") ... etc... 
3

You want to use the while loop to keep asking for input when the user didn't input something properly. Inside of you while loop, usr_input never changes, so it just keeps looping.

You also have another issue: you should keep looping only if usr_input is not 1 AND is not 2. not 1 or not 2 is always true (if it is 2, it is not 1, and if it is 1 it is not 2).

usr_input = input("Input: ")
while (usr_input != '1') and (usr_input != '2'): usr_input = input("Input: ")
if usr_input == '1': search()
elif usr_input == '2': sys.exit()
4

input() performs the equivalent of eval(raw_input()), so if your user inputs something syntactically incorrect, it will throw a SyntaxError exception. See the docs:

You could improve your code by catching the SyntaxError and handling it, so it doesn't crash your program.

3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy