首页 > 解决方案 > 为什么 IDLE shell 中出现这个 NameError?

问题描述

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)]

标签: pythonpython-3.xpython-idle

解决方案


>>> bn

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

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

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()asinput()隐式调用eval()输入的值


推荐阅读