python - 来自输入函数的 NameError

标签 python

<分区>

我想制作一个程序,询问您的年龄,然后从那里告诉您是否可以开车。如果用户输入的是字母或符号而不是数字,我希望它重新提出问题。

输入:

J

错误:

Python "Programs\welcome.py", line 3, in <module>
    age = str(input("How old are you?: "))
  File "<string>", line 1, in <module>
NameError: name 'J' is not defined

代码:

while True:
    age = str(input("How old are you?: "))
    if int(age) > 15 and age.isdigit:
        print ("Congradulations you can drive!")
    elif int(age) < 16 and age.isdigit:
        print ("Sorry you can not drive yet :(")
    else:
        print ("Enter a valid number")

最佳答案

您似乎在 Python 2 解释器中运行 Python 3 代码。

区别在于 Python 3 中的 input() 的行为类似于 Python 2 中的 raw_input()

此外,age.isdigit 并没有像您期望的那样调用 isdigit() 函数。相反,它只是确认函数存在。

一旦您修复了 isdigit() 问题,您还会遇到另一个错误:您正在执行 int(age) 转换之前确定它仅由数字组成。

Python 2 程序

while True:
    age = raw_input("How old are you?: ")
    if age.isdigit() and int(age) > 15:
        print "Congradulations you can drive!"
    elif age.isdigit() and int(age) < 16:
        print "Sorry you can not drive yet :("
    else:
        print "Enter a valid number"

Python 3 程序

while True:
    age = input("How old are you?: ")
    if age.isdigit() and int(age) > 15:
        print ("Congradulations you can drive!")
    elif age.isdigit() and int(age) < 16:
        print ("Sorry you can not drive yet :(")
    else:
        print ("Enter a valid number")

请注意,这两种实现都可以通过更改条件来进一步改进,但这超出了问题的范围。

关于python - 来自输入函数的 NameError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35110929/

相关文章:

python - 在 python/pandas 中如何搜索最近的值?

python - 如何在不拆分字符串的情况下展平列表?

python - Python ctypes 和 librsvg 出错

python - Selenium 中有没有办法从谷歌表单(python)的下拉菜单中选择一个选项

python - 如何使用spark session 导入python文件?

python - Pandas:将列表从列值映射到列?

python - 如何在Python中获取matlab脚本的输出

python - 有没有更简单的方法将 xml 文件解析为嵌套数组?

python - 如何知道一个点是否在图像中的一组点之外?

python - 自动以正确的编码打开文件