Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

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

  1. Oct 12, 2016 #1
    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.


    Code (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="")
     
  2. jcsd
  3. Oct 12, 2016 #2

    jedishrfu

    Staff: Mentor

    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.
     
  4. Oct 12, 2016 #3
    I edited the code little bit and removed the end="", and I added "abc" into the c loop printout

    Code (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 Im 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
    Code (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
     
  5. Oct 12, 2016 #4

    BvU

    User Avatar
    Science Advisor
    Homework Helper
    Gold Member

    You want to print the value of a, b and c. Not the strings "a", "b", "abc"
     
  6. Oct 12, 2016 #5

    jtbell

    User Avatar

    Staff: Mentor

    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.
     
  7. Oct 12, 2016 #6
    Why would I want to print the values instead of the strings
     
  8. Oct 12, 2016 #7
    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?
     
  9. Oct 12, 2016 #8

    FactChecker

    User Avatar
    Science Advisor
    Gold Member

    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.
     
  10. Oct 12, 2016 #9

    Ibix

    User Avatar
    Science Advisor

    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.
     
  11. Oct 13, 2016 #10

    Mark44

    Staff: Mentor

    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. (
    Code (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.
     
  12. Oct 14, 2016 #11

    ChrisVer

    User Avatar
    Gold Member

    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
     
  13. Oct 14, 2016 #12

    ChrisVer

    User Avatar
    Gold Member

    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:
    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: Oct 14, 2016
  14. Oct 14, 2016 #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: Oct 14, 2016
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted



Similar Discussions: Nested For-loop confusing, how does program proceed?
Loading...