Python Traceback(最近一次调用最后一次)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35493899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:31:04  来源:igfitidea点击:

Python Traceback (most recent call last)

pythonpython-2.7

提问by Mohamed Ali Benmansour

I am getting an error executing this code:

执行此代码时出现错误:

nameUser=input("What is your name ? ")    
print (nameUser)

The error message is

错误信息是

Traceback (most recent call last): File "C:/Users/DALY/Desktop/premier.py", line 1, in File "", line 1, in NameError: name 'klj' is not defined

回溯(最近一次通话):文件“C:/Users/DALY/Desktop/premier.py”,第 1 行,在文件“”,第 1 行,在 NameError 中:未定义名称“klj”

What's going on?

这是怎么回事?

采纳答案by mhawke

You are using Python 2 for which the input()function tries to evaluate the expression entered. Because you enter a string, Python treats it as a name and tries to evaluate it. If there is no variable defined with that name you will get a NameErrorexception.

您正在使用 Python 2,该input()函数尝试评估输入的表达式。因为您输入了一个字符串,所以 Python 将其视为一个名称并尝试对其求值。如果没有使用该名称定义的变量,则会出现NameError异常。

To fix the problem, in Python 2, you can use raw_input(). This returns the stringentered by the user and does not attempt to evaluate it.

要解决此问题,在 Python 2 中,您可以使用raw_input(). 这将返回用户输入的字符串,并且不会尝试对其进行评估。

Note that if you were using Python 3, input()behaves the same as raw_input()does in Python 2.

请注意,如果您使用的是 Python 3,则input()其行为与raw_input()Python 2 中的行为相同。

回答by timgeb

In Python2, inputis evaluated, input()is equivalent to eval(raw_input()). When you enter klj, Python tries to evaluate that name and raises an error because that name is not defined.

在 Python2 中,input被求值,input()相当于eval(raw_input()). 当您输入 klj 时,Python 会尝试评估该名称并引发错误,因为该名称未定义。

Use raw_inputto get a string from the user in Python2.

用于raw_input在 Python2 中从用户那里获取字符串。

Demo 1: kljis not defined:

演示 1:klj未定义:

>>> input()
klj
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'klj' is not defined

Demo 2: kljis defined:

演示2:klj定义:

>>> klj = 'hi'
>>> input()
klj
'hi'

Demo 3: getting a string with raw_input:

演示 3:获取字符串raw_input

>>> raw_input()
klj
'klj'