Ask coding questions

← Back to all posts
4
Code is wrong but I am unsure where and how...

https://repl.it/@HibaBiba/Age
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:

Commentshotnewtop
2
[deleted]

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
  else:
    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.

1

@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!

1
[deleted]

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

1
1
[deleted]

@HibaBiba ok and you're welcome.