当您使用python输入DOB时,创建一个以年为单位打印年龄的函数

时间:2019-09-10 00:41:38

标签: python python-3.x

经过100次尝试,我终于使它工作了,但是我想知道是否还有另一种编写此代码的方法,我是python的新秀,我将不胜感激。

import datetime

date= datetime.datetime.now()
def age_calc(age):
    age = date.year - int(dob)
    return age
dob=input("Please Enter DOB here: ")

print("You are %s years old" % age_calc(dob))

1 个答案:

答案 0 :(得分:0)

即使对于像这样的小型程序,也总会有一些东西需要改进和学习。一些建议:

  • 要明确显示变量名并正确!您将年龄作为age_calc的参数,但这实际上是date_of_birth。每个人都知道dob是什么,尽管最好将其拼写出来,尤其是在没有上下文的情况下。
  • 计算不正确,我出生于1983年11月5日,因此仍然是35岁,而不是您的程序告诉我的36岁
  • 您要索取DOB,但实际上您要求出生年月,总是很容易弄清楚所需的格式
  • 优良作法是对手动输入进行一些错误检查
  • 利用if __name__ == '__main__':构造并将程序拆分为可完成一项功能的多个函数。
  • 我个人很喜欢使用f弦f"Hello {name}"

请看一下下面的重构代码。

import datetime

def age_calc(date_of_birth):
    current_date = datetime.datetime.now()
    age_days = current_date - date_of_birth
    age_years = int(age_days.days / 365.25)
    return age_years

def get_date_of_birth():
    answered = False
    while not answered:
        dob_answer = input("Please Enter DOB here (DD-MM-YYYY) (enter q to quit): ")

        if dob_answer in ['q', 'Q']:
            exit()

        try:
            date_of_birth = datetime.datetime.strptime(dob_answer, "%d-%m-%Y")
            answered = True

        except ValueError:
            print(f"{dob_answer} has incorrect format, use: d-m-yyyy")

    return date_of_birth

def print_age(date_of_birth):
    print(f"You are {age_calc(date_of_birth)} years old")

if __name__ == '__main__':
    while True:
        dob = get_date_of_birth()
        print_age(dob)

祝你好运!