程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了名称“USER_INPUT”未定义? (Python 3.9.2)大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决名称“USER_INPUT”未定义? (Python 3.9.2)?

开发过程中遇到名称“USER_INPUT”未定义? (Python 3.9.2)的问题如何解决?下面主要结合日常开发的经验,给出你关于名称“USER_INPUT”未定义? (Python 3.9.2)的解决方法建议,希望对你解决名称“USER_INPUT”未定义? (Python 3.9.2)有所启发或帮助;

我正在尝试编写一个 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>",in <module>
nameError: name 'frIEs' is not defined

我见过有人在运行 Python 2 并使用 input() 而不是 raw_input() 时收到此错误,不过这在 Python 3 中应该不是问题。顺便说一句,当我省略从输入中排除数字的代码部分时,回文检查器工作正常。有什么想法吗?

解决方法

正如评论中提到的,你的第一个条件总是评估为真

试试这个:

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!
,

我现在设法解决了它,同时将其扩展为不允许数字字母组合。

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!')
,

我会告诉你你的代码有什么问题,函数 eval 需要一个字符串,这样如果字符串可以是一个函数,它就会生成函数,否则它会引发错误,当你在其中输入函数时,它会返回一个值,如果这个值 == 一个函数,那么使函数 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!')

    

大佬总结

以上是大佬教程为你收集整理的名称“USER_INPUT”未定义? (Python 3.9.2)全部内容,希望文章能够帮你解决名称“USER_INPUT”未定义? (Python 3.9.2)所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: