1

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!

Henry Ecker
35.8k19 gold badges48 silver badges67 bronze badges
asked Oct 16, 2021 at 2:13
2
  • 6
    There are many program visualization tools which can be helpful when learning. python tutor for example. Commented Oct 16, 2021 at 2:19
  • It might be easier to understand something a bit simpler, like for i in range(5): for j in range(5): print(i, j) Commented Oct 16, 2021 at 2:20

2 Answers 2

3

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.

answered Oct 16, 2021 at 2:23
Sign up to request clarification or add additional context in comments.

Comments

1

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

answered Oct 16, 2021 at 2:25

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.