You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 True loop: This runs forever until we explicitly break out of it with the break statement, ensuring we keep asking for input until it's valid.
  • try-except block:
    • The try section attempts to parse the user's raw input into a date object using your specified dd/mm/yyyy format.
    • If parsing fails (wrong format, invalid day/month combo), it throws a ValueError that we catch in the except block. We then show a friendly error message and let the loop restart to ask for input again.
  • Clean variable separation: We use birthDate_input to store the raw user input, then convert it to birthDate only once it's validated—this keeps the logic easy to follow.

内容的提问来源于stack exchange,提问作者C C

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 20:27:46