Learn with Yasir

Share Your Feedback

Python While Loop Exercise - Age and Input Validation | Code Example


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

Solution

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")

Explanation

Here’s a line-by-line explanation of the provided code:

1. Infinite Loop for Age Input

while True:
  • Starts an infinite loop that will keep running until explicitly broken (break).

2. Prompt User for Age Input

    age_input = input("Enter your age: ")
  • Asks the user to enter their age and stores it in age_input.

3. Check if Input is a Valid Number

    if not age_input.isdigit():
        print("Please enter a valid number.")
        continue
  • Checks if age_input is not a digit (i.e., not a valid number).
    • If not, it prints an error message and continue restarts the loop.

4. Convert Input to Integer and Validate Age

    age = int(age_input)
    if age <= 0:
        print("You haven't been born yet!")
        continue
  • Converts age_input to an integer (age).
  • Checks if age is ≤ 0 (invalid age).
    • If so, it prints a message and continue restarts the loop.

5. Exit the Loop if Age is Valid

    break
  • If the input passes all checks, break exits the loop.

6. Print a Blank Line for Readability

print()
  • Prints a newline for better formatting.

7. Prompt User for Name and Display

name = input("Enter your name: ")
print(f"Your name is {name} and you are {age} years old.")
print()
  • Asks for the user’s name and stores it in name.
  • Prints the name and age in a formatted string.
  • Prints another blank line.

8. Ask if User Likes Exercise (Initial Prompt)

exercise = input("Do you like to exercise? (Y/N) only: ").strip().upper()
  • Asks the user if they like exercise (expecting Y or N).
  • .strip() removes extra whitespace.
  • .upper() converts input to uppercase for case-insensitive comparison.

9. Validate Exercise Input (Must be ‘N’)

while exercise == "Y":
    print("Choose either Yes (Y) or No (N) only!")
    exercise = input("Do you like to exercise? (Y/N): ").strip().upper()
  • If the user enters "Y", the loop forces them to re-enter until they provide "N".
    • (Note: This logic is backwards—it should check for invalid inputs instead.)

10. Print Final Message

print()
print("Nice")
  • Prints a blank line followed by "Nice".

  • Python While Loops: Syntax, Examples & Best Practices – Learn how to use Python while loops with clear examples, syntax rules, and best practices. 👉 Learn more

🧠 Practice & Progress

Explore More Topics

Python Fundamentals

Flow Control Statements


Python Functions


Fundamentals more ...




🧠 Python Advanced

Object-Oriented Programming in Python (OOP)

More...

🧠 Modules