Home > Mobile >  Trying to make a month in a Calendar only used Nested Loops
Trying to make a month in a Calendar only used Nested Loops

Time:04-01

This is my code:

x = 8

while x <= 31:
    j = 1
    while j <= 7:
        print(j, "\t", end=' ')
        j  = 1
    print("\n")
    print(x, "\t", end=' ')
    x  = 7

The outcome is supposed to be where the month starts on a Sunday, starting from 1 - 31.

So far, this is the outcome of the code I have:

Sun Mon Tue Wed Thu Fri Sat

1 2 3 4 5 6 7

8 1 2 3 4 5 6 7

15 1 2 3 4 5 6 7

22 1 2 3 4 5 6 7

29

I can't figure out how to get the second line to continue with 9-14 and so on.

CodePudding user response:

Make a new line on each 7th day

for x in range(1, 32):
    print(x, end = ' ')
    if x%7==0:
        print('\n')

CodePudding user response:

You were setting j's value to 1 on each loop and that is why you were getting 1 2 3... values repeated in each line. You can use this:

while days <= 31:
    print(days, "\t", end = ' ')
    if days % 7 == 0: # Checking if it's a week or not. If yes, then moving to new line.
        print('\n')
    days  = 1

Output:

 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  31 

 
  • Related