我正在尝试制作一个Python程序,它接收一个字符串并计算它是否是回文(向后读取相同的内容)。我试图通过不允许数字作为输入来扩展它,这部分工作正常
a = eval(input('Put a word here: '))
if type(a) == int or float:
print('That\'s a number man.')
exit()
b = a[::-1]
if a == b:
print('The word is a palindrome!')
else:
print('The word is not a palindrome!')
但是,当我在cmd(使用Windows、Python 3.9.2)中使用一个随机单词(如“fries”)作为输入运行程序时,会出现以下错误:
Traceback (most recent call last):
File "C:\Users\Azelide\Desktop\folderr\hello.py", line 1, in <module>
a = eval(input('Put a word here: '))
File "<string>", line 1, in <module>
NameError: name 'fries' is not defined
我见过有人在运行Python2并使用input()而不是raw_input()时出现此错误,但在Python3中这应该不是问题。顺便说一下,当我省略代码中从输入中排除数字的部分时,回文检查器工作得很好。有什么想法吗
我将告诉您代码中的错误,函数eval接受一个字符串,因此,如果字符串可以是函数,它将使函数else产生错误,当您在其中输入函数时,它将返回一个值,如果该值==函数,则使函数else产生如下错误
现在,如果用户输入一个不能作为函数的值,它将引发如下错误
现在你可以照人们说的去做了
我现在已经设法解决了这个问题,同时扩展到不允许数字字母组合
如注释中所述,第一个条件的计算结果始终为true
试试这个:
输出:
相关问题 更多 >
编程相关推荐