Python年龄计算程序优化:如何通过While循环实现出生日期输入格式校验与异常重试
Adding Input Validation to Your Age Calculator
Got it, let's get this sorted for you! The issue with your current code is that it doesn't handle invalid input—if someone enters a date in the wrong format (or an impossible date like 32/01/2000), it crashes immediately. We'll fix this by wrapping the input/parsing logic in a while loop and using try-except blocks to catch errors, letting users try again until they enter a valid date.
Here's the revised code with validation:
import datetime as date def calculateAge(birthDate): today = date.datetime.today() age = today.year - birthDate.year - ((today.month, today.day) < (birthDate.month, birthDate.day)) return age # Loop indefinitely until we get a valid date while True: birthDate_input = input("Please enter your birthdate in the format (dd/mm/yyyy)\n>>> ") try: # Attempt to parse the input into a date object birthDate = date.datetime.strptime(birthDate_input, "%d/%m/%Y").date() break # Exit the loop once valid input is received except ValueError: # Catch invalid format/date errors and prompt user again print("Oops! That's not a valid date format or date. Please enter it as dd/mm/yyyy (e.g., 25/12/1990).") # Proceed with displaying birthday and age once input is valid print(f"Your birthday is on {birthDate.strftime('%d')} of {birthDate.strftime('%B, %Y')}") print("You are", calculateAge(birthDate), "years old")
Key changes explained:
while Trueloop: This runs forever until we explicitly break out of it with thebreakstatement, ensuring we keep asking for input until it's valid.try-exceptblock:- The
trysection attempts to parse the user's raw input into adateobject using your specifieddd/mm/yyyyformat. - If parsing fails (wrong format, invalid day/month combo), it throws a
ValueErrorthat we catch in theexceptblock. We then show a friendly error message and let the loop restart to ask for input again.
- The
- Clean variable separation: We use
birthDate_inputto store the raw user input, then convert it tobirthDateonly once it's validated—this keeps the logic easy to follow.
内容的提问来源于stack exchange,提问作者C C
相关产品推荐
相关产品推荐

