1
+ # importing the date module from the datetime package
2
+ from datetime import date
3
+
4
+ # defining a function calculate the age
5
+ def calculate_age (birthday ):
6
+
7
+ # using the today() to retrieve today's date and stored it in a variable
8
+ today = date .today ()
9
+
10
+ # a bool representing if today's day, or month precedes the birth day, or month
11
+ day_check = ((today .month , today .day ) < (birthday .month , birthday .day ))
12
+
13
+ # calculating the difference between the current year and birth year
14
+ year_diff = today .year - birthday .year
15
+
16
+ # The difference in years is not enough.
17
+ # We must subtract 0 or 1 based on if today precedes the
18
+ # birthday's month/day from the year difference to get it correct.
19
+ # we will subtract the 'day_check' boolean from 'year_diff'.
20
+ # The boolean value will be converted from True to 1 and False to 0 under the hood.
21
+ age_in_years = year_diff - day_check
22
+
23
+ # calculating the remaining months
24
+ remaining_months = abs (today .month - birthday .month )
25
+
26
+ # calculating the remaining days
27
+ remaining_days = abs (today .day - birthday .day )
28
+
29
+ # printing the age for the users
30
+ print ("Age:" , age_in_years , "Years" , remaining_months , "Months and" , remaining_days , "days" )
31
+
32
+ # main function
33
+ if __name__ == "__main__" :
34
+
35
+ # printing an opening statement
36
+ print ("Simple Age Calculator" )
37
+
38
+ # asking user to enter birth year, birth month, and birth date
39
+ birthYear = int (input ("Enter the birth year: " ))
40
+ birthMonth = int (input ("Enter the birth month: " ))
41
+ birthDay = int (input ("Enter the birth day: " ))
42
+
43
+ # converting integer values to date format using the date() method
44
+ dateOfBirth = date (birthYear , birthMonth , birthDay )
45
+
46
+ # calling the function to calculate the age of a person
47
+ calculate_age (dateOfBirth )
0 commit comments