calculate.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. # -*- coding: utf-8 -*-
  2. import time
  3. from calendar import isleap
  4. # judge the leap year
  5. def judge_leap_year(year):
  6. if isleap(year):
  7. return True
  8. else:
  9. return False
  10. # returns the number of days in each month
  11. def month_days(month, leap_year):
  12. if month in [1, 3, 5, 7, 8, 10, 12]:
  13. return 31
  14. elif month in [4, 6, 9, 11]:
  15. return 30
  16. elif month == 2 and leap_year:
  17. return 29
  18. elif month == 2 and (not leap_year):
  19. return 28
  20. name = input("input your name: ")
  21. age = input("input your age: ")
  22. localtime = time.localtime(time.time())
  23. year = int(age)
  24. month = year * 12 + localtime.tm_mon
  25. day = 0
  26. begin_year = int(localtime.tm_year) - year
  27. end_year = begin_year + year
  28. # calculate the days
  29. for y in range(begin_year, end_year):
  30. if (judge_leap_year(y)):
  31. day = day + 366
  32. else:
  33. day = day + 365
  34. leap_year = judge_leap_year(localtime.tm_year)
  35. for m in range(1, localtime.tm_mon):
  36. day = day + month_days(m, leap_year)
  37. day = day + localtime.tm_mday
  38. print("%s's age is %d years or " % (name, year), end="")
  39. print("%d months or %d days" % (month, day))