0

My codes asks for the age but how do I make it so that the age will always be a valid number and not words.

    while True:

        test = int(input("What is your age? "))
        if test > 0:
           print("has to be a number")
Sam
  • 43
  • 1

1 Answers1

-1

when int() can not parse the input() then it will raise a NameError. this you can catch and make sure to call the function again...

Try this:

def check_age():
    try:
        return int(input("What is your age? "))
    except NameError:
        print("Must be a number")
        return check_age()

if __name__ == '__main__':
    print(check_age())
Ivonet
  • 2,492
  • 2
  • 15
  • 28
  • How do I make it so that it asks the question again if its a letter and when I type a letter it comes up with : "ValueError: invalid literal for int() with base 10: 'ad' – Sam Dec 11 '17 at 12:00
  • see the check_age() call in the except block... a small typo... return check_age() :-) – Ivonet Dec 11 '17 at 12:01