【问题标题】:python 3 NameErrorpython 3名称错误
【发布时间】:2018-07-10 01:05:17
【问题描述】:

编辑:感谢您的有用回答!我下载了 Python 3.7.0,但你是对的,我的 Mac 运行的是 Python 2.7。我现在有作业:) 弄清楚如何让它运行 3.7。如果我有更多问题,我会回来的。谢谢!

这里是初学者。使用 Python Launcher 在 Mac 中执行时出现 NameError。在 Python 3.7.0 Shell 中进行测试时,它可以正常工作。我已经阅读了 NameError 问题的其他答案,但不明白我做错了什么。帮助表示赞赏。

使用的代码

first_name = input ("Hi, what's your first name? ")
print ("Hi," , first_name)

收到错误

Traceback (most recent call last):
  File "/Users/imperio/Documents/pythonpractice/Name.py", line 1, in <module>
   first_name = input ("Hi, what's your first name? ")
  File "<string>", line 1, in <module>
NameError: name 'Imperio' is not defined

【问题讨论】:

标签: python python-3.x nameerror


【解决方案1】:

这很可能是因为您没有使用 Python 3+ 执行它。

请检查python -V 的输出以查看您正在使用哪个版本执行代码。

在 mac 上,您可能已经安装了这两个版本,Python 3 有时别名为 python3 file.py

这是您转换为有效 Python2 的程序:

first_name = raw_input ("Hi, what's your first name? ")
print ("Hi, {}".format(first_name))

【讨论】:

    【解决方案2】:

    您正在运行 Python 2。在 Python 2 中,input 执行输入。 raw_input 只是返回输入的字符串。

    这是一个例子:

    >>> x = 1
    >>> y = 2
    >>> z = 3
    >>> print input('variable? ')
    variable? x                       # Note output is the value of the variable
    1
    >>> print input('variable? ')
    variable? w                          # Variable 'w' doesn't exist
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<string>", line 1, in <module>
    NameError: name 'w' is not defined
    >>> print raw_input('variable? ')       # Raw input just returns the input.
    variable? x
    x
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-02
      • 1970-01-01
      • 2012-03-28
      • 2016-05-03
      • 1970-01-01
      相关资源
      最近更新 更多