So I've searched quite a bit but haven't found something exactly similar to my question. My question is: I have a list of days in months. It looks like this:
daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
now, I already have a leap year formula that works out to change daysInMonth[1]
to 29
if it is a leapyear.
I need to sum up a select number of values in my list based on the user's entry of month. the reason for this, is the julian day is the number of days in the year to the date entered. so the user enters a date such as 1 31 2020
, and the julian day would be: 31
, so 2 2 2020
would be: 33
, and 12 31 2020
would be: 366
because its a leap year this year. Hopefully that makes sense.
I did this project back in high school on C++ and I'm trying to convert it to Python. The C++ version of what I'm trying to do looks like this:
int findingTheMonth(int daysInMonth[], int julianDay, int day, int month)
{
for (int i = 0; i < (month-1); i++)
{
julianDay = julianDay + daysInMonth[i];
}
julianDay = julianDay + day;
return julianDay;
}
My version in Python was this:
def findTheJulian(day, month, daysInMonth):
# sum together the months up until the users entered month
# then add the amount of days of the users entered month
julianDay = sum(daysInMonth[month-1]) + day
return julianDay
The reason this fails is because it says int object not iterable, but I don't understand why its giving me this. I'm not trying to change an integer or write over an integer... I'm trying to store a new value into julianDay by summing up a few elements of a list, and the users entered day.. What do I do? Also, I'm brand new in Python. There may be a lot of things that I don't quite understand yet, but I have a coding background and should be able to figure it out.
The problem is you are taking one element from daysInMonth. As example, if you pass
daysInMonth == [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
andmonth == 3
you get31
. Andsum(31)
raises error because you can't get sum of a number.The goal you want to reach is taking a slice of a list (all elements before
month
). Slice syntax islist[start:end]
. You can ignorestart
and set onlyend
, thenstart
will be 0.Your case:
julianDay = sum(daysInMonth[:month-1]) + day