Quantcast
Channel: Python Day Finder - Code Review Stack Exchange
Viewing all articles
Browse latest Browse all 3

Python Day Finder

0
0

I have made a Python program to find the day of the week of an inputted date. I did not want to use the time or datetime module, like in this answer, as I found that a bit too easy. (I like to challenge myself)

I want to improve on appropriately putting certain tasks in functions, so my program is easier to read and follow. I would like to know if the logic in my program makes sense, and if there is anything that could have been done easier. If things could have been in a more "Pythonic" way, that would be nice to know too.

Here is the code -

month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]day_names = ["Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday"]SYEAR = 2016SMONTH = 1SDAY = 1def is_leap_year(year):    if year % 4 == 0:        if year % 100 == 0:            if year % 400 == 0:                return True            else:                return False        else:            return True    return Falsedef calc_year(year):    days = 0    tyear = SYEAR    while not tyear == year:        if tyear < year:            if is_leap_year(tyear):                days += 366            else:                days += 365            tyear += 1        if tyear > year:            if is_leap_year(tyear - 1):                days -= 366            else:                days -= 365            tyear -= 1    return daysdef calc_month(month, year):    days = 0    tmonth = SMONTH    while not tmonth == month:        if tmonth == 2 and is_leap_year(year):            days += 1        days += month_days[tmonth - 1]        tmonth += 1    return daysdef calc_day(day):    days = 0    tday = SDAY    while not tday == day:        tday += 1        days += 1    return daysdef find_day(date):    total = calc_month(date[0], date[2]) + calc_day(date[1]) + calc_year(date[2])    if total < 0:        return day_names[total % -7]    else:        return day_names[total % 7]def main():    date = input("Enter a day like so <MM, DD, YYYY>: ").split()    month = int(date[0])    day = int(date[1])    year = int(date[2])    if month > 12 or month <= 0:        print("Invalid month")    elif day > month_days[month - 1] or day <= 0:        if not (day == 29 and month == 2):            print("Invalid day")    else:        print(find_day((month, day, year)))if __name__ == "__main__":    main()

I purposely start with the date 01 01 2016, because it is a leap year and (so far) has not had an effect on the outcome of the program.


Viewing all articles
Browse latest Browse all 3

Latest Images

Trending Articles





Latest Images