我想制作一个程序,询问您的年龄,然后从那里告诉您是否可以开车。如果用户输入的是字母或符号而不是数字,我希望它重新提出问题。
输入:
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")
请注意,这两种实现都可以通过更改条件来进一步改进,但这超出了问题的范围。