[英]NameError in simple python code
This is a simple palindrome checker. 这是一个简单的回文检查器。 The code works for numbers, but not strings. 该代码适用于数字,但不适用于字符串。
x = str(input("Enter a number: "))
if x == x[::-1]:
print x + " is a palindrome!"
else:
print x + " is not a palindrome!"
When I try inputting a string, I get this error: 当我尝试输入字符串时,出现此错误:
File "palindrome.py", line 1, in <module>
x = str(input("Enter a number: "))
File "<string>", line 1, in <module>
NameError: name 'abba' is not defined
It seems you are using Python 2.x! 看来您使用的是Python 2.x!
Please use raw_input
for keyboard input. 请使用raw_input
进行键盘输入。 This always returns a string, so there is no need to cast/convert. 这总是返回一个字符串,因此不需要强制转换。
In Python 2.x input
tries to evaluate the text entered as Python, and you never defined abba, so it will cause a NameError
在Python 2.x中, input
尝试评估输入为Python的文本,而您从未定义abba,因此它将导致NameError
Where you input some numbers.For example,"Enter a number: 1221".you can get 在其中输入一些数字的位置。例如,“输入数字:1221”。
x=str(1221) x = str(1221)
it's rigth. 这很严厉。
But, "Enter a number: abba".you can get 但是,“输入数字:abba”即可。
x=str(abba) x = str(abba)
it's wrong.Beacuse the "abba" is not string, and is not defined. 这是错误的。因为“ abba”不是字符串,并且没有定义。
you can try "Enter a number: 'abba'", or use 您可以尝试“输入数字:'abba'”,或使用
raw_input('Enter a number:') raw_input('输入数字:')
replace input("Enter a number: ") and You can get the results you want. 替换输入(“输入数字:”),即可获得所需的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.