Python equivalent for batch Choice command

Question:

I’m working on a small project in python, and after a bit of work on it I was wondering if there was a way of inputting data in python 3 which was somewhat similar to batch’s choice command. Pretty much only take in one key of input and then end the input prompt.

For example:

Choice(['Y', 'N'], "Yes or No? ")

Where the user could either press "Y" or "N" and the program would continue.

I’ve done some brief surfing, but haven’t found anything I can use.

Bonus:

What would be even more useful is if this "choice" command could except multiple characters.

Pretty much input but capping the limit of characters they can input, and then immediately continuing. The latter of which is proving to be hard.

Asked By: Monacraft

||

Answers:

There’s no built-in for this, but you could do something like this:

def choice(options, prompt):
    while True:
        output = input(prompt)    # Use raw_input(prompt) for Python 2.x
        if output in options:
            return output
        else:
            print("Bad option. Options: " + ", ".join(options))

This would let the user enter in arbitrary strings (of any length) into the command line, and would continue once the user hits enter. Unfortunately, there’s no easy way that I know of to automatically stop after a set number of characters.

However, this post does discuss ways of grabbing a single character from the command line. You may be able to adapt it into the above function so that it will automatically continue after a certain number of characters, without waiting for the enter key to be pressed.

Answered By: Michael0x2a