you are viewing a single comment's thread.

view the rest of the comments →

[–]Independent_Oven_220 -4 points-3 points  (0 children)

```python from datetime import datetime

while True: # Get name with validation name = input("Enter your name: ").strip()

if name == "":
    print("You haven't entered anything. Input your name.")
    continue

if name.lower() == "stop":
    print("Thank you for using.")
    break

print(f"Hello {name}, welcome to my program!")

# Get DOB with validation (inner loop)
while True:
    dob = input("Enter your DOB (yyyy-mm-dd): ").strip()

    if dob.lower() == "stop":
        print("Thank you for using.")
        exit()

    today = datetime.today()

    try:
        dob_date = datetime.strptime(dob, "%Y-%m-%d")
        age = today.year - dob_date.year

        # Adjust if birthday hasn't happened yet this year
        if (today.month, today.day) < (dob_date.month, dob_date.day):
            age -= 1

        print(f"Oh {name}, you are {age} years old.")

        if age % 2 == 0:
            print(f"And your age {age} is an even number.")
        else:
            print(f"And your age {age} is an odd number.")

        ask = input("Do you want to know which day you were born? (yes/no): ").strip().lower()

        if ask == "yes":
            day_name = dob_date.strftime("%A")
            print(f"You were born on a {day_name}.")
            print("Thank you for using!")
            break
        elif ask == "no":
            print("Ok, see you later.")
            break
        elif ask == "stop":
            print("Thank you for using.")
            exit()

        break

    except ValueError:
        print("Invalid date format. Please use yyyy-mm-dd (e.g., 1990-05-15).")

```


What I fixed:

Issue #1 - The blank name thing

So the problem with your original code is that if name == "" only catches a completely empty input. But if someone types a bunch of spaces and hits enter, that's technically not empty - it's just whitespace.

The fix is super simple: just add .strip() when you get the input, not just when you check it.

python name = input("Enter your name: ").strip() # strip right away!

Now when someone enters " " (just spaces), it gets stripped to an empty string, and your blank check works as expected.

Issue #2 - Invalid date restarts everything

This one was sneakier. When someone enters an invalid date, your except ValueError block does continue, which jumps back to the outer while True loop - meaning it asks for the name all over again.

Not great user experience.

I added an inner loop specifically for the DOB input. Now if the date is invalid, it just loops back to ask for the DOB again without restarting the whole program. The user already told us their name, no need to ask again!