-->

Python 4.3.1.8 LAB: Day of the year: writing and using your own functions

 Day of the year: writing and using your own functions

4.3.1.8 LAB
Day of the year: writing and using your own functions

Prerequisites

LAB 4.3.1.6

LAB 4.3.1.7

Objectives

Familiarize the student with:

  • projecting and writing parameterized functions;
  • utilizing the return statement;
  • building a set of utility functions;
  • utilizing the student's own functions.

Scenario

Your task is to write and test a function which takes three arguments (a year, a month, and a day of the month) and returns the corresponding day of the year, or returns None if any of the arguments is invalid.

Use the previously written and tested functions. Add some test cases to the code. This test is only a beginning.


Stoooooooop .. we are here to real the REAL PYTHON, not this SILLY COURSE

Dear learner  .. if you reached here, that means you'd have had enough of this boring course already😏. Let's learn python the right way, not the old school way.

Solution Code:

def is_leap_year(year): # LAB 4.3.1.6 A leap year
    if year % 4 != 0:
        return False
    elif year % 100 != 0:
        return True
    elif year % 400 != 0:
        return False
    else:
        return True


def days_in_month(year, month): #LAB 4.3.1.7 How many days
    if year < 1 or month < 1 or month > 12:
        return None
    days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    res  = days[month - 1]
    if month == 2 and is_leap_year(year):
        res = 29
    return res


def day_of_year(year, month, day): #LAB 4.3.1.8 Day of the year
    days = 0
    for m in range(1, month):
        md = days_in_month(year, m)
        if md == None:
            return None
        days += md
    md = days_in_month(year, month)
    if day >= 1 and day <= md:
        return days + day
    else:
        return None

print(is_leap_year(1900))
print(days_in_month(2021, 11))
print(day_of_year(2000,2,29))

Output:

  • False
  • 30
  • 60

=================================================================================

Follow the Python page on the Blog to be the first to know






Post a Comment

0 Comments