Josh C Josh C - 1 month ago 11
Python Question

NameError from input function

I want to make a program that asks your age then from there tells you whether you can drive or not. I want it to re-ask the question if the user inputs a letter or symbol instead of a number.

Input:

J


Error:

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


Code:

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")

Answer Source

You appear to be running Python 3 code in a Python 2 interpreter.

The difference is that in input() in Python 3 behaves like raw_input() in Python 2.

Furthermore, age.isdigit doesn't call the isdigit() function as you would expect. Rather, it just confirms that the function exists.

Once you fix the isdigit() problem, you also have another bug: you're performing the int(age) conversion before ascertaining that it consists only of digits.

A Python 2 program

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"

A Python 3 program

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")

Note that both of these implementations could be further improved by changing the conditionals, but that's beyond the scope of the question.