Skip to content

Commit 15f2d8d

Browse files
Age Calculator: fix leap-year function and add time summary (days→hours/minutes/seconds)
1 parent 5675c6d commit 15f2d8d

File tree

1 file changed

+27
-18
lines changed

1 file changed

+27
-18
lines changed

Age Calculator/calculate.py

Lines changed: 27 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,25 @@
11
import time
22
from calendar import isleap
33

4-
def judge_leap_year(year):
5-
if isleap(year):
6-
return True
7-
else:
8-
return False
4+
# Check if a year is a leap year
5+
def judge_leap(year: int) -> bool:
6+
return isleap(year)
97

10-
def month_days(month, leap_year):
8+
# Return number of days in a month, considering leap years
9+
def month_days(month: int, leap_year: bool) -> int:
1110
if month in [1, 3, 5, 7, 8, 10, 12]:
1211
return 31
1312
elif month in [4, 6, 9, 11]:
1413
return 30
1514
elif month == 2 and leap_year:
1615
return 29
17-
elif month == 2 and (not leap_year):
16+
else:
1817
return 28
1918

20-
19+
# User input
2120
name = input("Please enter your name: ")
22-
age = input("Please enter your age: ")
21+
age = int(input("Please enter your age: "))
22+
2323
localtime = time.localtime(time.time())
2424

2525
year = int(age)
@@ -29,16 +29,25 @@ def month_days(month, leap_year):
2929
begin_year = int(localtime.tm_year) - year
3030
end_year = begin_year + year
3131

32+
# Count days in past years
3233
for y in range(begin_year, end_year):
33-
if (judge_leap_year(y)):
34-
day = day + 366
34+
if judge_leap(y):
35+
day += 366
3536
else:
36-
day = day + 365
37+
day += 365
3738

38-
leap_year = judge_leap_year(localtime.tm_year)
39+
# Add days from current year
40+
leap_year = judge_leap(localtime.tm_year)
3941
for m in range(1, localtime.tm_mon):
40-
day = day + month_days(m, leap_year)
41-
42-
day = day + localtime.tm_mday
43-
print("\n\t%s's age is %d years or " % (name, year), end="")
44-
print("%d months or %d days" % (month, day))
42+
day += month_days(m, leap_year)
43+
44+
# Approximate breakdown (ignores time of day)
45+
hours = day * 24
46+
minutes = hours * 60
47+
seconds = minutes * 60
48+
49+
print(f"\nHello {name}, you are approximately:")
50+
print(f" {day:,} days")
51+
print(f" {hours:,} hours")
52+
print(f" {minutes:,} minutes")
53+
print(f" {seconds:,} seconds old!")

0 commit comments

Comments
 (0)