Ask coding questions

← Back to all posts
Code is wrong but I am unsure where and how...
HibaBiba (3)
This code is to check if the age inputted is valid within a specific range, however, if the input was wrong the first time, and the second time the input is correct, the code still asks the user again for their age. What have I done wrong and how can I fix this?
Have a nice day c:


The correct code for your program would be

ageInput = False
while ageInput == False:
  age = int(input('What is your age? '))
  if age > 16 and age < 19:
    print("Age valid.")
    ageInput = True
    print('Age invalid.')
    ageInput = False

as in your code you only check for the validity once and then get stuck in an infinite loop as the if statement is not executed again since it is out of the loop.

mat1 (2273)

@Harmeet_SinghSi To make your code even more readable, you could do while not age_input: And if 16 < age < 19:. Not neccesary but it's a good habit to get in.

Please upvote my comment if it was helpful to you. Thanks!


@mat1 I know but I was trying to keep it beginner level so she would be able to understand it easily.


@HibaBiba ok and you're welcome.