Python Nested For-loop confusing, how does program proceed?

  • Thread starter Thread starter late347
  • Start date Start date
  • Tags Tags
    Confusing Program
Click For Summary
The discussion focuses on understanding the behavior of a triple nested for-loop in Python. Participants clarify that the program completes all iterations of the innermost loop before returning to the next iteration of the middle loop, which is nested within the outer loop. It is emphasized that the structure of nested loops requires finishing all steps within a loop before moving to the next outer loop iteration. Suggestions include using distinct variable names for loop control to enhance clarity and visualizing the loop structure as a tree to better grasp the flow of execution. The conversation also touches on the efficiency of using loops to avoid repetitive code.
late347
Messages
300
Reaction score
15
I was thinking about triple nested for loop with a simple thought exercise on my own. I was little bit confused about that third nested loop (print c loop)

With simple case of double nested loop, I think I understood how the program works. (only one nesting).
But I'm having some trouble imagining exactly what letters and how many of them will be printed in this exercise. I'm having trouble with following the logic of the triple nested loop.

In simple nested loop, with only two loops:

  1. the first loop takes one step. Then the program proceeds to the second loop and fulfilles the entire second loop.
  2. And then it returns to the second step, of the first loop, then it proceeds to fulfill the entire second loop.
  3. And then the program returns to the third step of the first loop, then the program proceeds to fulfill the entire second loop.
But it becomes little bit confusing for the third loop which is the C-loop.
Python:
for a in range(3):
    print("a",end="")
    for b in range(3):
        print("b",end="")
        for c in range(3):
            print("c",end="")
 
Technology news on Phys.org
Print a, b and c in the innermost loop where youre printing just c now and it should make more sense

Youll see something like counting In base 3.
 
I edited the code little bit and removed the end="", and I added "abc" into the c loop printout

Python:
for a in range(3):
    print("a")
    for b in range(3):
        print("b")
        for c in range(3):
            print("abc")

my understanding is that the program proceeds as follows:
  • 0-eth iteration of a loop, -->0eth iteration of b loop, 0eth,1st,2nd iterations of "abc" are printed (fair enough)
  • for some reason the program reverts back to the b loop (for some reason, why is this so I am having trouble here?)
  • why doesn't the program revert back into the 1st iteration of a loop instead?

here is the actual printout from the program also for your benefit
Python:
a
b
abc
abc
abc
b
abc
abc
abc
b
abc
abc
abc
a
b
abc
abc
abc
b
abc
abc
abc
b
abc
abc
abc
a
b
abc
abc
abc
b
abc
abc
abc
b
abc
abc
abc
 
You want to print the value of a, b and c. Not the strings "a", "b", "abc"
 
It might help to make things clear if you use different ranges for the three loops, e.g. 3, 4, 5 instead of 3, 3, 3.
 
  • Like
Likes jedishrfu
BvU said:
You want to print the value of a, b and c. Not the strings "a", "b", "abc"
Why would I want to print the values instead of the strings
 
late347 said:
for some reason the program reverts back to the b loop (for some reason, why is this so I am having trouble here?

The b loop is within the a loop. Why are you expecting the program to go to the next iteration of the a loop before the enclosed b loop has been completed?
 
The c-loop is acting within each b-loop step exactly the way the b-loop is acting within each a-loop step. The Python mandatory indentation is very helpful in keeping nested loops straight. You can see that in your printout. It might help to indent the prints the same way you have indented the code.
 
late347 said:
Why would I want to print the values instead of the strings
Because then you can see directly how the variables controlling the looping are changing. It's not obligatory, but I agree with @BvU that it's a good way to see what's going on here.
 
  • Like
Likes jedishrfu
  • #10
It might help you understand better if you used different variables for your loop control variables. Here is a modification of your code from post #1. (
Python:
for i in range(3):
    print("a",end="")
    for j in range(3):
        print("b",end="")
        for k in range(3):
            print("c",end="")
Having loop control variables named a, b, and c, and loops that print "a", "b", and "c" makes it harder to understand, IMO. Now i, j, and k each take on the values 0, 1, and 2.

The outer loop runs 3 times. Each iteration of the outer loop causes the middle loop to run three times. Each iteration of the middle loop causes the innermost loop to run three time. So when the program is finished, the outer loop will have run three times; the middle loop will have run nine times; the innermost loop will have run twenty-seven times.
 
  • #11
you can also try to make a tree with that? it can help you imagine what goes on... it would look like this
Screenshot from 2016-08-27 18-09-56.png
 
  • #12
late347 said:
for some reason the program reverts back to the b loop (for some reason, why is this so I am having trouble here?)

I guess the easiest way to understand this is by having in your mind that once the program sees a "for" it goes all about finishing whatever is within it before returning and going to the next step of iteration or leaving out... you go into a-loop - you have to iterate and finish everything within... when you enter you see the b-loop - again you have to iterate and finish everything within... when you enter you see the c-loop - you finish everything and iterate over it... c-loop finishes iterations and goes out, b loop can continue iterating...and so on and so on.
For that reason you don't return to the 1st for, but to the 2nd... (because the 2nd is met within the 1st and it is not over yet)... that's why sketching it as a tree can help you (move up only once you finished everything in a line, starting from the top left to finish on the bottom right as I sketched it)

For loops help you save effort for writing hundrends of repeative unnecessary lines...
in particular you could have done exactly the same thing by writing the following code:
Python:
for i in range(3):
    print("a")
    for j in range(3):
        print("b")
        print("c")
        print("c")
        print("c")
in expense of extra lines of code...and well three chars are easy to handle by typing, but for example if the ranges were going up to 100 I don't think it'd be clever to write 100 lines of code just for that (or just say print("bcccc...ccc") with 100 c's)
 
Last edited:
  • #13
I will look into this matter maybe tomorrow. I feel down now because we had a tough exam today.

I ran out of time because I didnt manage time optimally in that exam.

I did too many math and physics prob even though I had some homework credit in the bag which helps the grade in math and physics. Where as in the exam compartments about programming&databases and the second compartment webdesign&text editing I didnt have homework credit opportunity.

I suppose it would not matter if:

You never make mistakes in math, therefore no need for double checking. (I usually double check my work...if possible and if it seems sensible to the situation)

You always calculate physics and math super fast. (Sometimes yes sometimes no...)
Especially in physics it probably helps to identify easy probs and finish them first.
 
Last edited by a moderator:

Similar threads

  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 8 ·
Replies
8
Views
3K
  • · Replies 66 ·
3
Replies
66
Views
6K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 10 ·
Replies
10
Views
2K
Replies
1
Views
2K
  • · Replies 66 ·
3
Replies
66
Views
22K
  • · Replies 19 ·
Replies
19
Views
2K
  • · Replies 14 ·
Replies
14
Views
34K