Question: Goal: Recap input validation using loops. Assignment: In this assignment, you are tasked with creating a basic program that performs input validation using a while

Goal: Recap input validation using loops.
Assignment: In this assignment, you are tasked with creating a basic program that performs input validation using a while loop. Your program will prompt the user to enter their age, and the input must meet specific criteria to be considered valid. The program will keep asking the user for input until a valid entry is provided.
Input Validation Requirements:
The input must be a positive integer between 0 and 120.
If the user enters a negative number, the program should inform the user that the age must be positive.
If the user enters a non-numeric value (such as letters or symbols), the program should inform the user that the input must be a valid number.
The program should use a while loop to repeatedly ask for input until the user enters a valid age.
Your program should produce an output similar to the following sample run:
Sample Run
Please enter your age: -5
Invalid input! Age must be between 0 and 120.
Please enter your age: abc
Invalid input! Please enter a valid number.
Please enter your age: 130
Invalid input! Age must be between 0 and 120.
Please enter your age: 25
Thank you! You entered a valid age: 25
Note: Assuming that the user's input has been stored in the variable user_input, use the user_input.isdigit() method to check if it consists only of digits.
My code
while True:
user_input = input('Please enter your age:
')
# check to see if its a number
if not user_input.isdigit():
print('Invalid input! Please enter a valid number.')
user_input = input('Please enter your age:
')
valid_age = int(user_input)
if valid_age <0 or valid_age >120:
print('Invalid input! Age must be between 0 and 120.')
else:
print(f'Thank you! You entered a valid age: {valid_age}')
break

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!