【问题标题】:Why this NameError in IDLE shell? [closed]为什么 IDLE shell 中出现这个 NameError? [关闭]
【发布时间】:2021-10-20 18:55:27
【问题描述】:
print('What is your name?')    # ask for their name
myName = input()  
print('It is good to meet you, ' + myName) 
print('The length of your name is:')
print(len(myName))

当我运行它时...

What is your name?
>>> bn
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    bn
NameError: name 'bn' is not defined

版本

>>> import sys; print(sys.version)
3.9.7 (tags/v3.9.7:1016ef3, Aug 30 2021, 20:19:38) [MSC v.1929 64 bit (AMD64)]

【问题讨论】:

  • 只搜索错误信息“[python] NameError: name 'bn' is not defined”。恐怕从您提供的内容来看,该错误是不可重现的。作为这里的新用户,也请带上tour并阅读How to Ask
  • 什么意思?你真的不应该使用 Python2 并且你的代码在 Python3 中运行良好
  • @MicTest 请将所有代码和回溯放在问题本身中,以便其格式正确。
  • 这看起来像是 Py2 与 Py3 的区别。如果您希望它在 Py2 下工作,请尝试“raw_input”而不是“input”。但是你不应该再使用 Py2...
  • 如何,究竟你在运行这个?

标签: python python-3.x python-idle


【解决方案1】:

&gt;&gt;&gt; bn

这意味着您在解释器 shell 上输入了bn,而不是之前的输入函数......

你可能想写这个而不是先打印

myName = input('What is your name? ')

您的错误也可能与 Python2 相关

例子

$ cat /tmp/app.py
print('What is your name?')    # ask for their name
myName = input()
print('It is good to meet you, ' + myName)
print('The length of your name is:')
print(len(myName))
$ python2 /tmp/app.py
What is your name?
bn
Traceback (most recent call last):
  File "/tmp/app.py", line 2, in <module>
    myName = input()
  File "<string>", line 1, in <module>
NameError: name 'bn' is not defined
$ python3 /tmp/app.py
What is your name?
bn
It is good to meet you, bn
The length of your name is:
2

如果你想使用Python2,你需要使用raw_input(),因为input()在输入的值上隐式调用eval()

【讨论】:

  • 但是我已经清楚地解释了我的版本。它是 IDLE shell 3.9.7
  • Python 3.9.7 (tags/v3.9.7:1016ef3, Aug 30 2021, 20:19:38) [MSC v.1929 64 bit (AMD64)] on win32 输入“help”,“ copyright”、“credits”或“license()”了解更多信息。 >>> print('你好,世界!') 你好,世界!
  • 好的,现在输入您问题的前两行。
  • 谢谢。这行得通。但我的疑问还没有消除。
  • >>> myName = input('你叫什么名字?') 你叫什么名字? kkhh >>> print(myName) kkhh
【解决方案2】:

您的环境一定有问题。您应该考虑卸载 Python 2。但是,请尝试运行此代码并告诉我们输出是什么:

import sys
print(sys.version[:5])
print('What is your name?')    # ask for their name
myName = input()  
print('It is good to meet you, ' + myName) 
print('The length of your name is:')
print(len(myName))

从 Py3.9 在 IDLE 中运行它,我得到以下输出:

Python 3.9.7 (tags/v3.9.7:1016ef3, Aug 30 2021, 20:19:38) [MSC v.1929
64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or
"license()" for more information.
>>> 
==== RESTART: C:\Users\Gary\Google Drive\Projects\StackOverflow\69651615.py ====
3.9.7
What is your name?
bn
It is good to meet you, bn
The length of your name is: 2
>>>

【讨论】:

  • 我正在运行版本 3
  • 但您更改了代码中的第 3 行
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-13
  • 1970-01-01
  • 2013-07-28
  • 2019-08-15
  • 1970-01-01
  • 2011-01-13
相关资源
最近更新 更多