while loop for checking if input mathces the criteria

Question:

I have to use the while loop for creating following function:

def ask_user(age_limit: int) -> int:

Ask a user their age using input("What is your age?").

This process must be repeated until a correct age is entered.

The age is correct if:

  • it is numeric -> otherwise print "Wrong input!" and ask to put the input age again
  • it is greater or equal to the age_limit -> otherwise print "Too young!" and ask to put the
    input age again
  • it is less or equal to 100 -> otherwise print "Too old!" and ask to put the input age again

If the age is correct, the function returns the correct age as an integer.

An example (with age_limit 18):

What is your age? a
Wrong input!
What is your age? 10
Too young!
What is your age? 101
Too old!
What is your age? 21
(function returns 21)

I am a beginner in Python and I do not know how to write this code.

I have tried:

def ask_user_age(age_limit: int) -> int:

    age = int(input("What is your age?"))
    while True:
        if not age.isdigit:
            print("Wrong input!")
        elif int(age) < age_limit:
            print("Too young!")
        elif int(age) > 100:
            print("Too old!")
    else:
        return age

But this does not work! Please help me 🙂

Answers:

You need to move the input() call inside the loop, so you get a new age if any of the validation checks fail.

You need to add () after isdigit to call the function.

else: return age needs to be inside the loop. Otherwise, the loop never ends.

def ask_user_age(age_limit: int) -> int:
    while True:
        age = input("What is your age?")
        if not age.isdigit():
            print("Wrong input!")
        elif int(age) < age_limit:
            print("Too young!")
        elif int(age) > 100:
            print("Too old!")
        else:
            return age
Answered By: Barmar
def ask_user(age_limit):
while True:
    age = input("What is your age?")
    if not age.isnumeric():
        print("Wrong input!")
    elif int(age) < age_limit:
        print("Too young!")
    elif int(age) > 100:
        print("Too old!")
    elif int(age)==age_limit:
        print(age)
   # For example age limit is 21
   ask_user(21)
Answered By: SMHD
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.