Pergunta

I am trying to write a program to print out a calendar that will print out the numbers in line with the days they fall on. I have it almost worked out, but I don't know how to make the numbers break to a new line after Sunday. Right now the code looks like this:

class Month:
    def __init__(self, nDays, day1):
        self.nDays = nDays
        self.day1 = day1

    def displayCalendar(self):
        week = ' S  M  T  W  T  F  S '
        print week
        days = 1
        if self.day1 == 2:
            print '  ',
        elif self.day1 == 3:
            print '     ',
        elif self.day1 == 4:
            print '        ',
        elif self.day1 == 5:
            print '           ',
        elif self.day1 == 6:
            print '              ',
        elif self.day1 == 7:
            print '                 ',

        for i in range(self.nDays):
            print '', days,
            days = days + 1

print '     APRIL 2014'
april2014 = Month(30,3)
april2014.displayCalendar()

As it stands now, I can start the month on the proper day, but the numbers just continue off the edge of the screen and don't come back to Monday.I know it is probably some stupid little detail, but I can't figure it out for the life of me.

Foi útil?

Solução

The following code will produce the desired result (note: it makes use of string formatting):

class Month:
    def __init__(self, nDays, day1):
        self.nDays = nDays
        self.day1 = day1

    def displayCalendar(self):
        week = ' S  M  T  W  T  F  S '
        print week
        days = 1
        if self.day1 == 2:
            print '  ',
        elif self.day1 == 3:
            print '     ',
        elif self.day1 == 4:
            print '        ',
        elif self.day1 == 5:
            print '           ',
        elif self.day1 == 6:
            print '              ',
        elif self.day1 == 7:
            print '                 ',

        for i in range(self.nDays):
            print '{:2}'.format(days),
            if (self.day1 + i) % 7 == 0:
                print ''
            days = days + 1

print '     APRIL 2014'
april2014 = Month(30,3)
april2014.displayCalendar()

[OUTPUT]
      APRIL 2014
 S  M  T  W  T  F  S 
       1  2  3  4  5 
 6  7  8  9 10 11 12 
13 14 15 16 17 18 19 
20 21 22 23 24 25 26 
27 28 29 30
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top