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