Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

python - How Do I Make a List of Numbers Line Break at a Certain Point?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...