3

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")
pppery
  • 3,731
  • 22
  • 33
  • 46
Josh C
  • 153
  • 1
  • 2
  • 6

2 Answers2

4

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.

200_success
  • 7,286
  • 1
  • 43
  • 74
0

You're looking for raw_input instead of input.

input will evaluate whatever string it receives, which isn't what you intended to happen.

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173