Python Workout 02 - Calculations with Functions

Overall Difficulty:

Objective: This workout provides more practice with creating basic functions incorporating calculations and handling datetime.

Problem 1: Create a function that takes two arguments: the original price and the discount percentage as integers and returns the final price after the discount.

Example:

final_price(discount = .5, price = 20) ➞ 10

Problem 2: Create a function that takes the age in years and returns the age in days.

Example:

calc_age(65) ➞ 23725

Problem 3: Create a function, get_days, that takes two dates and returns the number of days between the first and second date

Example:

get_days(05-20-1994, 05-21-1994) ➞ 1

Submission

SImply post your code and a screenshot of your results.

Please format your Python code and blur it or place it in a hidden section.

This workout will be released on Thursday March 30, 2023, and the author’s solution will be posted on Wednesday April 5, 2023.

1 Like

import datetime

def final_price(discount, price):
if (type(discount) != int or type(price) != int):
print(“Please enter both values as integer number(s)”)
return
reduced_price = price - (discount/100)*price
return print(“Final price after discount is:”,reduced_price)

final_price(15,125)

def cal_age(num_age):
current_year = datetime.datetime.now().year
dob_year = current_year - num_age
leap_year_days = 0
while dob_year < current_year:
if (dob_year % 4) == 0:
leap_year_days +=1
dob_year+=1

age_indays = num_age* 365 + leap_year_days

return print("Age in days (inc. leap years) is:", age_indays)

def get_days(start_date, end_date):
days_difference = datetime.datetime.strptime(start_date,“%m-%d-%Y”) - datetime.datetime.strptime(end_date,“%m-%d-%Y”)
days_difference = days_difference.days

return print(f'Day difference between {start_date} and {end_date} is {days_difference} days')

cal_age(34)
get_days (‘03-31-2023’,‘03-01-2023’)

1 Like

Great work here @Neb.

image

1 Like

Ok love the consistency @JordanSchnurman! Great work here

1 Like

hmmm maybe the age difference should be absolute values.

@kedeisha1

Summary

I did one part of it and will come back. I thought I’d visit your workout area. Glad you’re on here @kedeisha1

Update: I added some text output.

Summary

1 Like

Hi, here’s my solution.

I didn’t apply any type check because it’s not required by the statement.

My calc_age function doesn’t take leap years into consideration, because it would be required to know precisely the years, not only the range (1900÷1964 is not the same as 2000÷2064)

def final_price(discount, price):
    return price * (1 - discount / 100)

image


def calc_age(yrs):
    return yrs * 365

image


from datetime import datetime

def get_days(d1, d2):
    d1 = datetime.strptime(d1, "%m-%d-%Y")
    d2 = datetime.strptime(d2, "%m-%d-%Y")
    return abs((d2 - d1).days)

image

Here are my solutions:

Problem 1:

def final_price(price, discount):
    '''This function applies a discount to an original price'''

    return price * discount

print(final_price(.5, 20))

Problem 2

def age_count(age):
    '''This function takes in any age and returns the amount of days'''

    return age * 365.25

Problem 3

def get_days(first_date, second_date):
    '''This function returns the absolute value of the difference of two dates'''

    first_date = datetime.datetime.strptime(first_date, '%m-%d-%Y')
    second_date = datetime.datetime.strptime(second_date, '%m-%d-%Y')

    return abs((second_date - first_date).days)

print(get_days('05-20-1994', '05-20-2023'))

I decided to do mine without using any datetime libraries or do any input checks. Also I did mine backwards YYYY-MM-DD as its the standard way (but not what was asked … sorry)

def daysbetween(year1,month1, day1, year2, month2, day2):
    result = 0
    #Swap dates
    if year1*10000+month1*100+day1 > year2*10000+month2*100+day2:
        return daysbetween(year2,month2, day2, year1,month2, day1)
    else:
        
        #First Year
        months = [31,28,31,30,31,30,31,31,30,31,30,31]
        leapmonths = [31,29,31,30,31,30,31,31,30,31,30,31]
        if year1%4 == 0: result = 366 - sum(leapmonths[:month1-1])-day1   
        else: result = 365 - sum(months[:month1-1])-day1
        
        if year1 == year2: return result - sum(months[month2-1:])+ day2

        #Loop through years
        for i in range(year1+1, year2):
            result += 365 + i%4==0
        
        #Final Year
        if year2%4 == 0: result = result + 366 - sum(leapmonths[month2-1:])+ day2  
        else: result = result + 365 -  sum(months[month2-1:])+ day2  

    return result 

#Split the string
def getPeriod(myDate):
    return [int(i) for i in myDate.split("-")]

#Call the function
def get_days(x,y):
    return daysbetween(*getPeriod(x), *getPeriod(y))