input():“ NameError:未定义名称'n'”

发布于 2021-01-29 18:35:42

好的,所以我正在用python编写成绩检查代码,我的代码是:

unit3Done = str(input("Have you done your Unit 3 Controlled Assessment? (Type y or n): ")).lower()
if unit3Done == "y":
    pass
elif unit3Done == "n":
    print "Sorry. You must have done at least one unit to calculate what you need for an A*"
else:
    print "Sorry. That's not a valid answer."

当我通过python编译器运行它并选择时"n",出现一条错误消息:

“ NameError:未定义名称’n’”

当我选择"y"我再NameError'y'是问题,但是当我做别的事情,代码运行正常。

任何帮助是极大的赞赏,

谢谢。

关注者
0
被浏览
186
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    raw_input在Python
    2中使用来获取字符串,input在Python
    2中等效于eval(raw_input)

    >>> type(raw_input())
    23
    <type 'str'>
    >>> type(input())
    12
    <type 'int'>
    

    因此,当您输入类似的内容时ninput它会认为您正在寻找一个名为的变量n

    >>> input()
    n
    Traceback (most recent call last):
      File "<ipython-input-30-5c7a218085ef>", line 1, in <module>
        type(input())
      File "<string>", line 1, in <module>
    NameError: name 'n' is not defined
    

    raw_input 工作良好:

    >>> raw_input()
    n
    'n'
    

    帮助raw_input

    >>> print raw_input.__doc__
    raw_input([prompt]) -> string
    
    Read a string from standard input.  The trailing newline is stripped.
    If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
    On Unix, GNU readline is used if enabled.  The prompt string, if given,
    is printed without a trailing newline before reading.
    

    帮助input

    >>> print input.__doc__
    input([prompt]) -> value
    
    Equivalent to eval(raw_input(prompt)).
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看