Search code examples
pythonfunctionloopslogic

Function which asks for age


I need this to ask for an age, but if the age is under 11 or over 100 to reject it and to also reject anything but integers. If a number put in is out of the given range or isn't an integer I need it to loop back and ask again

def PlayerAgeFunction():
   VALID = True
   while VALID == True:
      PlayerAge = int(raw_input('ENTER YOUR AGE: '))
      if PlayerAge == type(int):
          VALID = False
     elif PlayerAge != type(int):
         print 'THAT IS NOT A NUMBER.'
   return PlayerAge

I looked on here for an answer before but what I found didn't help. please can someone help, thank you.


Solution

  • def prompt_age(min=11, max=100):
        while True:
            try:
                age = int(raw_input('ENTER YOUR AGE: '))
            except ValueError:
                print 'Please enter a valid number'
                continue
            if not min <= age <= max:
                print 'You are too young/old'
                continue
            return age