【问题标题】:Simple python code is not working [duplicate]简单的python代码不起作用[重复]
【发布时间】:2025-12-24 20:10:14
【问题描述】:

以下代码不起作用:

person = input('Enter your name: ') 
print('Hello', person)

它没有打印Hello <name>,而是给了我以下回溯:

Traceback (most recent call last):
  File  "C:/Users/123/Desktop/123.py", line 1, in <module> 
    person = input('Enter your name: ') 
  File "<string>", line 1, in <module>
NameError: name 'd' is not defined

【问题讨论】:

  • 您使用的是什么版本的 Python?这看起来像 Python 2 错误,如果是,您应该使用 raw_input()
  • 你是怎么运行这个的?在命令行、IDE 等上?代码中没有 d,所以你得到这个答案很奇怪。
  • 你应该补充说你输入了这个“d”
  • 在开始使用 Python 时,重要的是要清楚您使用的是 Python 2.7 还是 Python 3.x。 2017 年,建议那些不维护旧代码库的人使用 3.x。因此,如果您使用哪个并不重要,您可以通过更改您使用的 Python 来解决上述问题,而不是更改代码。无论哪种方式,请注意此类问题。

标签: python input output python-2.x


【解决方案1】:

要读取字符串,您应该使用:

person = raw_input("Enter your name: ")
print('Hello', person)

当您使用input 时,它会读取数字或引用变量。当您使用Python 2.7 或更低版本时会发生这种情况。使用Python 3 及更高版本,您只有input 功能。

您的错误表明您输入了“d”,这是一个未在代码中声明的变量。

所以如果你有这个代码:

d = "Test"
person = input("Enter your name: ")
print('Hello', person)

你现在输入“d”作为名字,你会得到输出:

>>> 
('Hello', 'Test')

【讨论】:

    【解决方案2】:

    什么是错误?

    你用过这个:

    person = input('Enter your name: ') 
    

    你应该用过这个:

    person = raw_input('Enter your name: ') 
    

    为什么这些不同

    input 尝试评估传递给它的内容并返回值,而 raw_input 只读取一个字符串,这意味着如果您只想读取一个字符串,则需要使用 raw_input

    在 Python 3 中,input 消失了,raw_input 现在称为 input,尽管如果您真的想要旧行为 exec(input()) 具有旧行为。

    【讨论】: