Python 选择限制器

Python selection limiter

我正在做一个项目,我必须要求用户做出选择,我必须将他们的答案限制在 1-4 之间,并在他们做出不可接受的选择时让程序通知他们。当我尝试修改限制器以在用户输入空 space 作为输入时不会崩溃时,我的问题就出现了。

无论我如何更改下面的代码,我都会收到无效语法错误。关于如何解决此错误的任何建议?我不知道它是否与布尔值无关,但这是我添加的导致错误的代码部分。原来限制器是教官给的整个class

def questionHairstyle():
    while True:
        hairchoice = ()
        questionsH = ("        1, for bald;" "\n" "        2, for crew-cut;"
        "\n" "        3, for curly;" "\n"   "        4, for wearing a hat;")
        print("Please enter a hairstyle:")
        print(questionsH)
        hairchoice = input("--> ", )
        print()
        if hairchoice[0] >= "1" and hairchoice[0] <= "4" 
        and not hairchoice[0] == " " and len(hairchoice) ==1:
        break
        print("Choice must be, between 1-4, not ", hairchoice + ".")
        print("Try again.")

准确的错误信息。

File "C:\Python34\Projects\sketch\sketch4.py", line 34
    if hairchoice[0] >= "1" and hairchoice[0] <= "4"
                                                    ^
SyntaxError: invalid syntax

最后的代码

所以首先是缩进。如果不缩进 defwhile,Python 解释器将理解 while 语句 函数之外定义。但是因为函数中没有定义任何东西,Python 引发了一个 IndentationError,怀疑是哪里出了问题。

EDIT 所以实际上,您还有另一个问题:您的 if 语句有两行。 Python不理解这个,所以万一出错了,他会提出一个SyntaxError。为避免这种情况,只需在 if 语句的第一行末尾放置一个反斜杠 \ :

if hairchoice[0] >= "1" and hairchoice[0] <= "4" \
and not hairchoice[0] == " " and len(hairchoice) ==1:

之后,如果您在 input 函数中输入空结果,您将得到 SyntaxError。如 What's the difference between raw_input() and input() in python3.x? 所述,Python2 将尝试将输入评估为 Python 代码。如果您只需要一个字符串,可以使用 raw_input.

来避免这种情况

最后但同样重要的是,如果您只按 Enter 键,您将得到一个 IndexError。原因是您有一个空字符串 "" 并且您尝试获取该字符串的第一个索引。有两种处理方法:

第一个是改变你条件的顺序,把len(hairchoice) == 1放在第一个位置。如果第一个为假,则不会评估其他人。

第二个是限制允许的字符串。 if 语句将如下所示:if hairchoice in ["1", "2", "3", "4"]:

def questionHairstyle():
    while True:
        hairchoice = ()
        questionsH = ("        1, for bald;" "\n" "        2, for crew-cut;"
        "\n" "        3, for curly;" "\n"   "        4, for wearing a hat;")
        print("Please enter a hairstyle:")
        print(questionsH)
        hairchoice = raw_input("--> ")
        print()
        if hairchoice in ["1", "2", "3", "4"]:
            break
        print("Choice must be, between 1-4, not ", hairchoice, ".")
        print("Try again.")

我有来自@FunkySayu 的即兴代码。

def questionHairstyle():
    while True:
        questionsH = ["    1, for bald;",
                "    2, for crew-cut;",
                "    3, for curly;",
                "    4, for wearing a hat"
                ]
        print("Please enter a hairstyle:")
        print("\n".join(questionsH))
        hairchoice = raw_input("-->")  #This will take even spaces
        print()
        if hairchoice in ["1", "2", "3", "4"]:
            break
        elif hairchoice == " ":     #This part checks for space as input from user
            print ("Space is encountered ")
            print("Choice must be, between 1-4, not ", hairchoice, ".")
            # This part of code can be extended for other user input also
        print("Try again.")


questionHairstyle()

输出:

Please enter a hairstyle:
    1, for bald;
    2, for crew-cut;
    3, for curly;
    4, for wearing a hat
--> 
()
Space is encountered 
('Choice must be, between 1-4, not ', ' ', '.') #You can see the ' ' space is identified well in the output.
Try again.
Please enter a hairstyle:
    1, for bald;
    2, for crew-cut;
    3, for curly;
    4, for wearing a hat
-->