Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return day of the year with a for loop that takes the month & day as input

I need to write a function called day_of_the_year that takes a month and day as input and returns the associated day of the year. Let the month by a number from 1 (representing January) to 12 (representing December). For example:

day_of_the_year(1, 1) = 1
day_of_the_year(2, 1) = 32
day_of_the_year(3, 1) = 60

Use a loop to add up the full number of days for all months before the one you're interested in, then add in the remaining days. For example, to find the day of the year for March 5, add up the first two entries in days_per_month to get the total number of days in January and February, then add in 5 more days.

So far, I have made a list:

days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

This is my code so far:

def day_of_the_year(month,day):
    days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    for number in day_of_the_year:
        total = days_per_month[0] + days_per_month[1] + 5
        return total

Is there something that I am missing?

like image 579
roTenshi2 Avatar asked Oct 19 '25 10:10

roTenshi2


1 Answers

Yes, you are exiting your loop on the first pass every time.

What you should do is define the total variable outside of the for loop and then increment it on each iteration.

You also only need to iterate to the month that is specified so use the range function to loop. And since day_of_the_year is the name of the function, it will cause an error if you try to put it in a for loop.

Then once the loop has finished you can add the days to total and return it.

def day_of_the_year(month,day):
    days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    total = 0
    for number in range(month - 1): 
        total += days_per_month[number]
    return total + day

print(day_of_the_year(1,1))
print(day_of_the_year(12,25))

output:

1
359

Michael's solution is the better solution to getting the answer, I just want to help you understand what you were missing and how to make it work.

like image 149
Alexander Avatar answered Oct 22 '25 00:10

Alexander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!