Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 7 Online
OpenStudy (anonymous):

Why two -for- can rebound the variable and give this output? edx.org/courses/MITx/6.00x/2012_Fall/discussion/forum/600x_l3_v3/threads/5077eff65308862b00000059

OpenStudy (anonymous):

After the first iteration of the inner loop, the ui variable is set to 2. However, since the inner loop has already begun when the ui was set to 4, it will iterate four times... that's why you get the 0,1,2,3 numbers printed out initially. On the same reasoning, the outer loop will also iterate four times, however the second time the inner loop executes, the ui is set to 2, that's why you get the 0,1 numbers printed out. The same will happen for the 3rd and 4th iteration of the inner loop. Does that make sense?

OpenStudy (anonymous):

Ok, my comparisson with ui=4 for i in range(ui): print i ui=2 was clouding my understanding. It's not that you can't re-bound the range value, it's just that by the range is over it just goes to the next piece of code. But if the loop is inside another loop you can re-run it with another range value re-bound inside itself. Thanks

OpenStudy (anonymous):

Indeed! Glad to be of help!

OpenStudy (anonymous):

Let me try to explain: Calling the method range(ui) with ui= 4 is calculated and results in the tupel [0,1,2,3] and is used for the outer loop with parameter j. Now we have the same calculation for the first inner loop. ui is 4 so tupel is again [0,1,2,3]. For each run of the loop this tupels are constant and can not be changed by giving ui a new value. So for the first inner loop 0 1 2 3 are printed out and ui is changed to 2. Now the second outer loop starts, for the inner loop calling range(ui) results now in the tuple [0,1]. This results in the print output 0 1 of the innerloop. As two futher runs of the outer loop are left, the generated output of inner loop is 0 1 for each run. All in all we have 0 1 2 3 0 1 0 1 0 1 as output of your code

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!