简体   繁体   中英

Returning a variable instead of its assigned range

So I'm trying to write a program that calculates the date from a day out of the year (out of 365) and I'm having this problem in which I cannot get my for loop to work properly with python's range function. Ie\\

Day = input("Enter day: ")
january = range(1,32)
february = range(32,59)
etc....
months = [january,february,etc....]
for i in months
    if Day in i:
        return i

However this only ever returns range(x,y). I need it to return a position in the months array. Such as if day is 31 then it should return the [0] position (i=0), if day is 360 then it returns [12]. Is my for loop written wrong? My other solution to this would be telling it to return the variable name instead of what range it has assigned to it, however I have no idea how to do this.

The direct answer to your question is to user enumerate() to give the index:

for month, i in enumerate(months):

However, this seems like an overly complicated way to solve this problem. An alternative solution is to store the number of days in each month:

months = [31, 28, 31, etc.]

Then use plain ol' arithmethic as you loop over this list:

for days, month in enumerate(months):
    if Day <= days:
        return month+1, day
    Day -= days

Note that this completely eliminates the need for you to calculate the first and last number for each month. I don't know about you, but I'd rather let the computer do the math than do it myself. Also, I still use enumerate here. Finally, I am returning both the month number and the day which basically reconstructs the calendar date. The +1 is to make January start at 1 instead of 0.

A python range has the .index(value, [start, [stop]]) function, giving the index of a value in the range. This returns the first index of the value found, or raises a ValueError if it is not present.

Just return the index of i in months . Also, note, if Day is 31 and it returns the 0 , then Day=360 should return 11 since the last index of months is 11 not 12 .

Day = input("Enter day: ")
january = range(1,32)
february = range(32,59)
etc....
months = [january,february,etc....]
for i in months:
    if Day in i:
        return months.index(i)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM