Home > other >  Beginner Nested Loops Python
Beginner Nested Loops Python

Time:10-16

Beginner here in an intro to programming class at Uni learning Python. I understood most of it until loops and now I am very confused.

Can someone explain why this creates the pattern that it outputs?

for i in range(1, 7):
    for j in range(6, 0, -1):
        print(j if j <= i else " ", end = " ")
    print()

outer loop triggers and (i = 1)

then inner loop triggers and (j = 6)

then it doesn't print j (6) because 6 <= 1 is False and prints 2 blank spaces.

Then at this point does the inner loop end and then goes back to the outer loop for the next iteration?

or does the inner loop continue until 6-1 hits 1?

and if the inner loop continues, does i stay 1 the entire inner loop or does it also go up per each inner loop iteration?

i really hope this makes sense. thank you!

CodePudding user response:

The inner loop continues until it is exhausted, counting down with j going from 6, to 5, to 4 and so on until on the last iteration j is 0. While it does so the outer loop doesn't progress: i remains 1. Only once the inner loop finishes does the outer loop get a chance to repeat. So then i advances to 2 and the inner loop starts all over from 6 again.

CodePudding user response:

First outer loop: i = 1 inner loop iterates: j = 6, 5, 4, 3, 2, 1 And is False, False, False, False, False, True So produces " 1"

Second outer loop: i = 2 inner loop iterates: j = 6, 5, 4, 3, 2, 1 And is False, False, False, False, True, True So produces " 2 1"

Third outer loop: i = 3 inner loop iterates: j = 6, 5, 4, 3, 2, 1 And is False, False, False, True, True, True So produces " 3 2 1"

etc

  • Related