【问题标题】:error in python d not defined. [duplicate]python d中的错误未定义。 [复制]
【发布时间】:2011-02-06 11:07:23
【问题描述】:

我正在学习 python 并且有这个错误。我可以弄清楚代码中的错误在哪里。 File "<string>", line 1, in <module>.

Name = ""
Desc = ""
Gender = ""
Race = ""
# Prompt user for user-defined information
Name = input('What is your Name? ')
Desc = input('Describe yourself: ')

当我运行程序时

它输出 你叫什么名字? (我输入 d)

这给出了错误

Traceback (most recent call last):
  File "/python/chargen.py", line 19, in <module>
    Name = input('What is your Name? ')
  File "<string>", line 1, in <module>
NameError: name 'd' is not defined

这是绝对初学者的 Python 3 示例代码。

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    在 Python 2.x 中,input() 需要 Python 表达式,这意味着如果您键入 d,它会将其解释为名为 d 的 变量。如果你输入"d",那就没问题了。

    您可能真正想要的 2.x 是 raw_input(),它将输入的值作为原始字符串返回,而不是计算它。

    由于您遇到了这种行为,看起来您使用的是 2.x 版本的 Python 解释器 - 相反,我会转到 www.python.org 并下载 Python 3.x 解释器,这样它就可以匹配你正在使用的书。

    【讨论】:

      【解决方案2】:

      您可能正在使用 Python 2.x,其中inputeval 用户输入。仅在 Python 3.x 中 input() 返回原始用户输入。

      您可以通过在控制台中运行 python 来检查 Python 的版本,例如这是 Python 2.6:

      ~$ python
      Python 2.6.5 (r265:79063, Apr  5 2010, 00:18:33) 
      [GCC 4.2.1 (Apple Inc. build 5659)] on darwin
      Type "help", "copyright", "credits" or "license" for more information.
      >>> 
      

      您可以通过python3.1 运行特定版本的 Python(例如 3.1):

      ~$ python3.1
      Python 3.1.1 (r311:74480, Jan 25 2010, 15:23:53) 
      [GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin
      Type "help", "copyright", "credits" or "license" for more information.
      >>> 
      

      【讨论】:

      • 您好 kennyTM 非常感谢!是的,它看起来像版本冲突:( Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GCC 4.4.1] on linux2 将升级我的 python 版本。如果没有我永远不会想出来你们再次感谢:)
      【解决方案3】:

      在 Python 3.0 及更高版本中,您正在使用的书讲授,input() 做了 raw_input() 在 Python 2 中所做的事情,所以在这种情况下代码是正确的;但是,您似乎使用的是旧版本的 Python(2.6?)。

      我建议您转至Python website 并下载最新版本的 Python 3,以便您更轻松地阅读本书。


      鉴于您使用的是 Python 2,直接的问题是您使用的是input(),它会评估您提供的任何内容。您要做的是获取用户输入的原始字符串:

      Name = raw_input("What is your Name? ")
      

      Python 3.x 和 2.x 之间有很多细微的差别,所以如果你想继续使用绝对初学者的 Python 3,一定要获取最新的 Python 3。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-17
        • 2015-03-01
        • 1970-01-01
        • 2020-04-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多