【问题标题】:input(): "NameError: name 'n' is not defined" [duplicate]输入():“NameError:名称'n'未定义”[重复]
【发布时间】:2013-06-29 02:34:28
【问题描述】:

好的,所以我正在用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: name 'n' is not defined"

当我选择"y" 时,我得到另一个NameError 'y' 是问题所在,但是当我执行其他操作时,代码运行正常。

非常感谢任何帮助,

谢谢。

【问题讨论】:

    标签: python terminal nameerror


    【解决方案1】:

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

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

    所以,当您在 input 中输入类似 n 的内容时,它认为您正在寻找一个名为 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)).
    

    【讨论】:

      【解决方案2】:

      您在 Python 2 上使用 input() function。请改用 raw_input(),或切换到 Python 3。

      input() 在给定的输入上运行eval(),因此输入n 被解释为python 代码,寻找n 变量。您可以通过输入 'n'(所以加上引号)来解决这个问题,但这不是一个解决方案。

      在 Python 3 中,raw_input() 已重命名为 input(),完全取代了 Python 2 中的版本。如果您的资料(书籍、课程笔记等)以期望n 起作用的方式使用input(),您可能需要改用Python 3。

      【讨论】:

        猜你喜欢
        • 2018-08-01
        • 2020-06-17
        • 2016-07-06
        • 2015-10-22
        • 2016-05-12
        • 2011-11-19
        • 1970-01-01
        • 1970-01-01
        • 2017-09-14
        相关资源
        最近更新 更多