1

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.

Thanks in advance, Mona

4

1 回答 1

1

没有内置的,但你可以这样做:

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))

这将允许用户在命令行中输入任意字符串(任何长度),并且一旦用户点击enter. 不幸的是,我知道没有简单的方法可以在设定的字符数后自动停止。

但是,这篇文章确实讨论了从命令行获取单个字符的方法。您也许可以将其改编为上述功能,使其在一定数量的字符后自动继续,而无需等待enter按键被按下。

于 2013-09-09T04:51:20.820 回答