5
\$\begingroup\$

I am new to python and to the StackExchange sites. I made an age calculator but i want to improve it till it's a reliable thing. Can i shorten the code? What can be Done more? Does it need any additions?

Thanks in advence.

from datetime import datetime

print("A simple program to calculate your age")
print()

date = datetime.now()
year = int(date.year)
month = int(date.month)
day = int(date.day)
input_year = int(input("Enter the year you were born: "))
if input_year <= 0 or input_year > 2020:
    print("don't you know your birthday??")
    exit()
input_month = int(input("Enter the month you were born: "))
if input_month <= 0 or input_month > 12:
    print("don't you know your birthday??")
    exit()
input_day = int(input("Enter the day you were born: "))
if input_day <= 0 or input_day > 31:
    print("don't you know your birthday??")
    exit()
age_year = year - input_year
age_month = month - input_month
if age_month < 0:
    age_year = age_year - 1
    age_month = 12 - (input_month - month)
age_day = day - input_day
if age_day < 0:
    age_month = age_month - 1
    age_day = 31 - (input_day - day)
print("you are " + str(age_year) + " years, " + str(age_month) + " months and " + str(age_day) + " days old.")
\$\endgroup\$
4
\$\begingroup\$

Generally, it is often not a good idea to hardcode values. For example, take a look at this piece of code. It won't work correctly from 2021 onwards:

if input_year <= 0 or input_year > 2020:
    print("don't you know your birthday??")

Better do it like this:

date = datetime.now()
current_year = int(date.year)

if input_year <= 0 or input_year > current_year:
    print("don't you know your birthday??")

This will make your program work in future years without the need to change the value for the current year manually.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Cool suggestion. will try it out! \$\endgroup\$ – LyZeN77 Aug 1 at 14:59
3
\$\begingroup\$
  1. Use exceptions.
  2. You are assuming number is entered by the user. What if I enter a character. You need to handle entry other than number and raise an error
  3. Ask user to enter birth date in format you wanted and then use subtract from today's date. Then convert to years and months. Both dates should be in same format to subtract.
| improve this answer | |
\$\endgroup\$
3
\$\begingroup\$

Time deltas in stock Python kind of suck. dateutil will make this easier for you; it has built-in support for total-year, total-month and total-day fields:

from datetime import date
from dateutil.relativedelta import relativedelta

print("A simple program to calculate your age\n")

birth_str = input('Enter the date you were born, in format YYYY-MM-DD: ')
try:
    birth = date.fromisoformat(birth_str)
except ValueError:
    print("Don't you know your birthday?")
    exit()

age = relativedelta(date.today(), birth)
print(f'You are {age.years} years, {age.months} months and {age.days} days old.')

Also note the use of:

  • String interpolation (f-strings)
  • Parsing a date from user input in one go, rather than as separate fields
| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Try using \n to the end of the print() statement, instead of using multiple statements.

You also need to think about error handling, what happens if the user enters a blank? or enters an invalid date?

To get the year, month or day from a date, you should use Python's built in datetime functionality: date.year

Also, when subtracting dates (to find the user's age), instead of figuring out whether the date is negative and subtracting months etc, try using Python's built-in timedelta function: (https://docs.python.org/3.3/library/datetime.html?highlight=datetime#timedelta-objects).

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$
  1. Use exception handling during inputs. You want the user to enter a number each time but it will not always be true. I might enter a blank by mistake. This will make your program to crash.
try:
    year = int(input('Enter your birth year')
except TypeError:
    print('You have to enter a number')
    # do something
  1. Use f-strings. They are faster. Realpython's guide can be helpful

  2. As mentioned by Flursch, it is not a good idea to hardcode values. Quoting directly

date = datetime.now() current_year = int(date.year)

if input_year <= 0 or input_year > current_year:
    print("don't you know your birthday??")

This will make your program work in future years without the need to change the value for the current year manually.

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.