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.
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)
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(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))