Python:For循环不按预期迭代

时间:2012-05-17 14:30:37

标签: python loops for-loop calendar

我试过写日历。但for循环只会打印出第一个月的日期。如果我尝试打印循环后的日子它将工作。有谁知道发生了什么?

cal_year = input('Enter a year (YYYY): ')

def not_common(year):
    if (year % 4 == 0):
        if (year % 100 == 0):
            if (year % 400 == 0):
                return 1
            else:
                return 0
        else:
            return 1
    else:
        return 0

leap = not_common(cal_year)

if leap == 0:
    print 'This is not a leap year'

elif leap == 1:
    print 'This is a leap year'

else:
    print 'unexpected calculation error'

y1900=1


day = ((cal_year-1900)*365)%7

month = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
calendar = [range(1,32), range(1,29), range(1,32), range(1,31), range(1,32), range(1,31),\
         range(1,32),range(1,32),range(1,31),range(1,32),range(1,31),range(1,32)]

if (leap == 1):
    calendar[1] = range(1,30)

week = ['su','mo','tu','we','th','fr','sa']
r = 0
for i in range(0,12):
    print month[i]
    print ' '.join(str(y) for y in week)
    for j in range (1, (len(calendar[i])/7)+2):
        #cal =' '.join(str(x).zfill(2) for x in calendar[i][r*7:7*(r+1)])
            print ' '.join(str(x).zfill(2) for x in calendar[i][r*7:7*(r+1)])
            r += 1   
    print

print calendar[1]
print calendar[11]

故障线被认为是:     ''。join(str(x).zfill(2)for x in calendar [i] [r * 7:7 *(r + 1)])

1 个答案:

答案 0 :(得分:1)

每次开始新的一个月时,您需要重新开始使用您的值r

您的代码还有其他问题,您假设每个月都在星期日开始,并且具有7天的确切倍数。