New coder looking for critique on fun project.

Joined
Jul 20, 2023
Messages
56
Reaction score
2
I'm teaching myself python. I wrote a fun program that asks your name and date of birth then tells you how old you are in several different formats such as house old you are in days or in months and days or in years, months, and days. I gotta add weeks but that will be easy. I know it's not perfect especially when it comes to calculating days only but it's damn close. In more interested in proper coding techniques. I'm sure the whole thing is probably very sloppy. I also have a strong feeling that I'm not using the def function the way it's intended. Please critique. Show me how you would've wrote it. Thanks.

Age_calc.py:

from datetime import datetime
import calendar
import os

current_day = datetime.now().day
current_month = datetime.now().month
current_year = datetime.now().year

repeat = "Y"
new_info = "Y"


def clear_screen():
# Check if the operating system is Windows
if os.name == 'nt':
os.system('cls') # For Windows
else:
os.system('clear') # For other platforms like macOS and Linux


def days_only(yrs, mos, dys, nm):
dys = dys+(yrs*365)+(mos*30)
print(nm, 'you are', dys, 'days old. Good God!')


def months_days(yrs, mos, dys, nm):
mos = mos+(yrs*12)
print(nm, 'you are', mos, 'months old and', dys, 'days old')


def years_months_days(yrs, mos, dys, nm):
print(nm, 'you are', yrs, 'years,', mos, 'months, and', dys, 'days old!')


clear_screen()


while repeat == "Y":

if new_info == "Y":
name = input("Hello. What is your name? ")
# birth_date = input(f'Okay {name}. Enter your birthday.: (MM/DD/YYYY)')
birth_year = input(f'Hello {name} what year were you born? ')
birth_month = input("What month numerically? (EX: December=12) ")
birth_day = input(f'And what day of the month of {calendar.month_name[int(birth_month)]}? ')

print('\n SEE YOUR EXACT AGE IN:')
print(' 1. DAYS ONLY \n 2. MONTHS AND DAYS ONLY \n 3. YEARS MONTHS AND DAYS \n 4. ALL OF THE ABOVE')
selection = input('\nENTER A NUMBER: ')
clear_screen()

birth_year = int(birth_year)
birth_month = int(birth_month)
birth_day = int(birth_day)
years = current_year - birth_year
months = current_month - birth_month
days = current_day - birth_day
if months < 0:
years = years - 1
months = 12 - abs(months)
if days < 0:
months = months - 1
days = 30 + days

if selection == '1':
days_only(years, months, days, name)
if selection == '2':
months_days(years, months, days, name)
if selection == '3':
years_months_days(years, months, days, name)
if selection == '4':
days_only(years, months, days, name)
months_days(years, months, days, name)
years_months_days(years, months, days, name)

if years < 36:
print("Good for you!")
else:
print("Damn. That's old!")

repeat = input("\nWould you like to try again? (Y/N): ").upper()

if repeat == "Y":
new_info = input('Enter new information? (Y/N):').upper()

clear_screen()

print('Thanks for stopping by', name)
 
Joined
Jul 4, 2023
Messages
354
Reaction score
41
Your forget in your calculation about leap year for every 4 years

e.g here
Python:
def days_only(yrs, mos, dys, nm):
    dys = dys+(yrs*365)+(mos*30)
    print(nm, 'you are', dys, 'days old. Good God!')

use datetime in calculation (leap year is calculated automatically ;))

check: calculate age in days with python
 
Joined
Dec 10, 2022
Messages
73
Reaction score
22
You're on a good start. Keep practicing and I recommend that you have a look at pythons' classes. Will make the job easier.
 
Joined
Jul 4, 2023
Messages
354
Reaction score
41
You can also try using the dateutil library

e.g. (without class-es using) [ on-line ]

Python:
'''
    Python 3.10+ required
    due to the use of:  match
    read more:  https://learnpython.com/blog/python-match-case-statement/
'''

from dateutil.relativedelta import relativedelta
from datetime import datetime
import calendar
import os



def clearScreen():
    os.system('cls' if os.name in ('nt', 'dos') else 'clear')


def show_age(year, month, day, selection):
    birth_date = datetime(year, month, day)
    delta = relativedelta(datetime.now(), birth_date)   
    
    match selection:
        case '1':
            date_diff = datetime.now() - birth_date
            return f'you are {date_diff.days} days old'
        case '2':
            return f'you are {delta.months} months old and {delta.days} days old'
        case '3':           
            print(("Damn. That's old!", 'Good for you!') [delta.years < 36])
            return f'you are {delta.years} years, {delta.months} months and {delta.days} days old'
        case _: # default action
            pass


repeat = 'y'
name = input('Hello. What is your name? ')

while repeat in ['y', 'Y']:
    clearScreen()   

    while True:
        try:
            birth_year  = int(input(f'Hello {name} what year were you born? '))
            if not len(str(birth_year)) == 4:
                print('Year must to be four digits number')
            #elif not birth_year in range(1800, datetime.now().year + 1):
            #    print('Your text about birth_year - out of range')
            else:
                break
        except ValueError:
            print('Use only digits')
            
    while True:
        try:
            birth_month  = int(input('What month numerically? (EX: December=12) '))
            if not len(str(birth_month)) in [1, 2]:
                print('Month must to be one or two digits number')
            elif not birth_month in range(1,13):
                print('Wrong month number')   
            else:
                break
        except ValueError:
            print('Use only digits')
            
    while True:
        try:
            birth_day  = int(input(f'And what day of the month of {calendar.month_name[birth_month]}? '))
            if not len(str(birth_day)) in [1, 2]:
                print('Day must to be one or two digits number')
            elif not birth_day in range(1,32):
                print('Wrong day number')     
            else:
                break
        except ValueError:
            print('Use only digits')
            
    while True:
        print('\n SEE YOUR EXACT AGE IN:')
        print(' 1. DAYS ONLY \n 2. MONTHS AND DAYS ONLY \n 3. YEARS MONTHS AND DAYS')
        selection = input('\nENTER A NUMBER: ')
        if not selection in ['1', '2', '3']:
            print('Please, use right option number')
        else:
            break
            
    clearScreen()

    print(name, show_age(birth_year, birth_month, birth_day, selection))

    repeat = input('\nWould you like to try again? (Y/N): ')

clearScreen()
print('Thanks for stopping by', name)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,516
Members
44,991
Latest member
Josephnag

Latest Threads

Top