Trouble understanding this second version of my previous code

Output should be:

1
3 2
6 5 4
10 9 8 7

start = 1
stop = 2
current_num = stop
for row in range(2, 6):
    for col in range(start, stop):
        current_num -= 1
        print(current_num, end=' ')
    print("")
    start = stop
    stop += row
    current_num = stop

For example I dont see how the second line starts with a 3… I’m really trying to nail this triangle pattern understanding.

Thanks!

On the first loop, start = 1, stop = 2 and current_num = stop

You then print current_num -= 1, which is 1.

start = stop which is 2

stop += row which is 2 + 2

You then have current_num = stop which is (as above) 4

You then loop again and decrement current_num by 1, which is the 3 that you are seeing on the second row.

To add:

You may find it helpful to include some ‘print debugging’ lines:

start = 1
stop = 2
current_num = stop
for row in range(2, 6):
    for col in range(start, stop):
        current_num -= 1
        print(current_num, end=' ')
    print("")
    print(f"\nDebug 1:\nstart:{start}\nstop:{stop}\nrow:{row}\n")
    start = stop
    stop += row
    current_num = stop
    print(f"Debug 2:\nstart:{start}\nstop:{stop}\nrow:{row}\n")
1 Like

When I was learning to program I was shown how to run the code of a program using pencil and paper.

I would write down the variables and as I read the code I would have to write down what the variables are set to.

If you do this for your code you should be able to reason out why it prints what it does.

Start with writing down start, stop, current_num, row and col.
Read the code statement by statement and update the values.
Keep track of which line of code you are running and what line of code is run next.

In this way you are the computer and its runs at your speed.

I still run code in my head this way to reason out how it works and why it works.

2 Likes

Thanks so much! Fully understand now. Part of my issue was a misunderstanding of what stop+=row meant. For some reason I has it in my mind stop was incrementing by 1, not by the value of row. I really appreciate it.

Dave

1 Like

I did a better job at trying this idea and it helped a lot, thanks.