Step-by-step solution for Python while loop exercise age and input validation. Learn how to solve this problem efficiently with clear explanations and example code. Perfect for beginners!
Click here to view problem statement
while True:
age_input = input("Enter your age: ")
if not age_input.isdigit():
print("Please enter a valid number.")
continue
age = int(age_input)
if age <= 0:
print("You haven't been born yet!")
continue
break
print()
name = input("Enter your name: ")
print(f"Your name is {name} and you are {age} years old.")
print()
exercise = input("Do you like to exercise? (Y/N) only: ").strip().upper()
while exercise != "N":
print("Choose either Yes (Y) or No (N) only!")
exercise = input("Do you like to exercise? (Y/N): ").strip().upper()
print()
print("Nice")
Here’s a line-by-line explanation of the provided code:
while True:
break
). age_input = input("Enter your age: ")
age_input
. if not age_input.isdigit():
print("Please enter a valid number.")
continue
age_input
is not a digit (i.e., not a valid number).
continue
restarts the loop. age = int(age_input)
if age <= 0:
print("You haven't been born yet!")
continue
age_input
to an integer (age
).age
is ≤ 0 (invalid age).
continue
restarts the loop. break
break
exits the loop.print()
name = input("Enter your name: ")
print(f"Your name is {name} and you are {age} years old.")
print()
name
.exercise = input("Do you like to exercise? (Y/N) only: ").strip().upper()
Y
or N
)..strip()
removes extra whitespace..upper()
converts input to uppercase for case-insensitive comparison.while exercise == "Y":
print("Choose either Yes (Y) or No (N) only!")
exercise = input("Do you like to exercise? (Y/N): ").strip().upper()
"Y"
, the loop forces them to re-enter until they provide "N"
.
print()
print("Nice")
"Nice"
.