0

我试图搜索这个错误,但我没有找到它,所以它是:

我尝试在 linux 中运行的 python 3 脚本中输入输入,它只能是 0-5。我使用以下代码执行此操作:

    while True:
        type = input("Please choose a type:\n1) a\n2) b\n3) c\n4) d\n0) EXIT\n"))

        if type == "0":
            sys.exit()

        elif type == "1" or type == "2" or type == "3" or type == "4":
            print("You entered: %s" %type )
            break

        else:
            os.system("clear")
            print("Input entered is invalid, please try again.\n")

当我输入数字时程序运行良好,但当我输入字母时它崩溃。请帮忙 :(

Traceback (most recent call last):
  File "test.py", line 21, in <module>
    type = input("Please choose a type:\n1) a\n2) b\n3) c\n4) d\n0) EXIT\n"))   
  File "<string>", line 1, in <module>
NameError: name 'h' is not defined
4

1 回答 1

1

input相当于eval(raw_input(prompt))

意味着您的输入被解释。这意味着数字、函数、var 将起作用,但文本不起作用。

改为使用raw_input。(见http://docs.python.org/2/library/functions.html#raw_input

注意:这是有效的 python 2,并且您提到了 python 3。但是,我认为您实际上使用的是 python 2,因为您的提示以 \n 结尾,它包含在 python 3 中,并且您的脚本适用于 python 3

于 2012-10-31T13:56:15.423 回答