Search code examples
pythonnested-loopsnested-lists

digits 0 to 9 in a triangle


I need help with a task in my intro to python programming course that requires a code that will print the following using two 'for-loops', one being nested:

0

0 1

0 1 2

0 1 2 3

0 1 2 3 4

0 1 2 3 4 5

0 1 2 3 4 5 6

0 1 2 3 4 5 6 7

0 1 2 3 4 5 6 7 8

0 1 2 3 4 5 6 7 8 9

So far i have come up with the following code, but my triangle of numbers begins at the digit 1 instead of 0:

for i in range(-1,9):
    print ('\n')
    for i in range (int(i+1)):
        j = i+1
        print (j, end=' ')

Can anyone advise what I should do to make my list of digits begin from 0 instead of 1? Also any suggestions on how to make my code more readable? Thanks.


Solution

  • When using range, if you want the last integer to be included, you need to add one. With this in mind, I think the following makes sense:

    for i in range(9+1):  # +1 since you want the loop to include 9
        for j in range(i+1):  # +1 since you want your print to include i
            print (j, end=' ')
        print ('\n')
    

    The print(\n) statement can go before or after your j for-loop, although the output will be slightly different. (Maybe because I'm used to mechanical typewrites, I think of \n as finishing a line rather than getting ready for a new one, but both are reasonable.)

    I don't like the idea of starting at -1 so you can then add 1 later. It's unduly complicated, and a bad habit to start with as a beginner.