名称“用户输入”未定义?(Python 3.9.2)

2024-10-02 16:21:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试制作一个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中这应该不是问题。顺便说一下,当我省略代码中从输入中排除数字的部分时,回文检查器工作得很好。有什么想法吗


Tags: the程序inputifhereputis错误
3条回答

我将告诉您代码中的错误,函数eval接受一个字符串,因此,如果字符串可以是函数,它将使函数else产生错误,当您在其中输入函数时,它将返回一个值,如果该值==函数,则使函数else产生如下错误

a = eval(input('enter a name: '))

现在,如果用户输入一个不能作为函数的值,它将引发如下错误

name'value that the user input' is not defined

现在你可以照人们说的去做了

a = input('Put a word here: ')

try:
    float(a)
    print('That\'s a number man.')
    exit()
except ValueError:
    for char in a:
        if char.isdigit():
            print('That\'s a combination of letters and numbers.')
            exit()

b = a[::-1]
if a == b:
    print('The word is a palindrome!')
else:
    print('The word is not a palindrome!')

    

我现在已经设法解决了这个问题,同时扩展到不允许数字字母组合

a = input('Put a word here: ')

try:
    float(a)
    print('That\'s a number man.')
    exit()
except ValueError:
    for char in a:
        if char.isdigit():
            print('That\'s a combination of letters and numbers.')
            exit()

b = a[::-1]
if a == b:
    print('The word is a palindrome!')
else:
    print('The word is not a palindrome!')

如注释中所述,第一个条件的计算结果始终为true

试试这个:

a = input('Put a word here: ')

for char in a:
    if char.isdigit():
        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!')

输出:

Put a word here: fries
The word is not a palindrome!

相关问题 更多 >