我该如何使这个代码运行完全没有错误,以便年龄是正确分配根据他们输入的日期?

2024-05-14 10:22:05 发布

您现在位置:Python中文网/ 问答频道 /正文

from random import randint
def main():
    dob = int(input("Please enter the year you were born"))
    if dob > (2005):
        main()
    elif dob < (2004):
        main()
    else:
        def mob():
            if dob == (2004):
                month = input("Please enter the first three letters of the month you were born")
            if month == ("Jan","JAN","jan","Feb","FEB","feb","Mar","MAR","mar","Apr","APR","apr","May","MAY","may","Jun","JUN","jun","Jul","JUL","jul"):
                age = 12
            elif month == ("Aug","AUG","aug"):
                day = int(input("Please input the day you were born"))
                if day < 28:
                    age = 12
                elif day == ("29","30","31"):
                    age = 11
                else:
                    age = 12
            else:
                age = 11
                if dob == (2005):
                    age = 11
       mob()
main()

如果我进入2004年,然后是8月,那就不会问那一天了出生代码将停止。我还希望代码能够运行,这样如果我进入2005年,它会将年龄指定为11岁


Tags: theyouinputageifmaindefelse
1条回答
网友
1楼 · 发布于 2024-05-14 10:22:05

像这样的东西确实满足了你的需要,我想,尽管你可以通过使用datetime来进一步整理它以给出实际的年龄。你知道吗

def main():
    yob = int(input("Please enter the year you were born"))
    if yob > 2005:
        return  "Under 11" 
    elif yob < 2004:
        return  "Over 12"
    elif yob == 2004:
        return 12
    else:
        mob = input("Enter a three letter abbreviation for your month of birth: "
        if mob.lower() in ("jan", "feb", "mar", "apr", "may", "jun", "jul"):
            return  12
        elif mob.lower() == "aug":
            dob = int(input("Enter your day of birth"))
            if dob < 28:
                return  12
            elif dob > 28:
                return  11
        else:
            return  11

age = main()

更好的选择,涵盖了我认为最不可能发生的事情

from datetime import datetime

def give_age():
    today = datetime.today()
    dob = input("Enter your date of birth (DD/MM/YYYY): ")
    try:
        dob_datetime = datetime.strptime(dob, "%d/%m/%Y")
        age = (today - dob_datetime).days / 365
        return age
    except ValueError:
        print("Your date of birth was not in the required format")
        give_age()
age = give_age()

相关问题 更多 >

    热门问题