首页 > 解决方案 > 基于DOB的Python年龄计算器

问题描述

我正在通过创建一个年龄计算器来练习,该计算器根据给定的出生日期计算年龄。

但是,它并没有按照我想要的方式工作。我想在用户的年龄为 19 且月份小于 6 时向用户显示年龄,例如 19,如果月份大于 6,那么我想在这种情况下为 19+1 的年龄加 1。

谁能以更好的方式创建具有相同概念的相同程序?请添加一些解释,以便我理解。

我是python初学者,所以请原谅我糟糕的代码以及我糟糕的英语。在此先感谢您的帮助。

from datetime import date

Doby,Dobm,Dobd =input("enter your DOB : i.e year,month,days  1999,02,08   : ").split(",")
born = date(year = int(Doby) , month= int(Dobm) , day= int(Dobd))
today = date.today()
age = today.year - born.year
condition = today.month - born.month
if condition >= 6 :
    age += 1
elif condition <= -6 :
    age -= 1
print(age)

标签: pythonpython-3.x

解决方案


假设今天是01/01/2019并且输入是12/06/1989。我们需要的输出是29years and 7 months.

   if  condition >= 0:
    Totmonth = condition 
  else:
     Totmonth = 12+condition 
      age -= 1

  print "age is" , age,"years and", Totmonth,"months"

推荐阅读