<- Back to the chapter.

Answer to Problem 9

Question:

Write code that will print the following:

0 1 2 3 4 5 6 7 8 9
  0 1 2 3 4 5 6 7 8
    0 1 2 3 4 5 6 7
      0 1 2 3 4 5 6
        0 1 2 3 4 5
          0 1 2 3 4
            0 1 2 3
              0 1 2
                0 1
                  0

Tip: This one is difficult. Two inside loops are needed. First, a loop prints spaces, then numbers. To start with, try writing a loop that prints:

0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6
0 1 2 3 4 5
0 1 2 3 4
0 1 2 3
0 1 2
0 1
0

Then once that is working, add a loop after the outside loop and before the inside loop. Use this new loop to print enough spaces to right justify the other loops.

Answer:

for row in range(10):

    for j in range(row):
        print (" ",end=" ")

    for j in range(10-row):
        print (j,end=" ")

    print()
Variables:
j=
row=
Output:
0 1 2 3 4 5 6 7 8 9
  0 1 2 3 4 5 6 7 8
    0 1 2 3 4 5 6 7
      0 1 2 3 4 5 6
        0 1 2 3 4 5
          0 1 2 3 4
            0 1 2 3
              0 1 2
                0 1
                  0

To make it clear where spaces are, you can turn underlines on or off.

Explanation:

Video: Answer to Problem 9