Shouldn't both blocks of code print similar results? Why is the range function inside of the inner loop reevaluated each time the inner for statement is reached while the range function in the outerloop is only evaluated once?
x = 4
for j in range(x)
for i in range(x)
print i
x = 2
Results
0
1
2
3
0
1
0
1
0
1
I know the first 4 integers printed ( 0 - 3) are a result of the code
for j in range(x): code but why are the the following also printed?
0
1
0
1
0
1
The code
x = 4
for j in range(x):
print i
x = 5
Prints
0
1
2
3
Additional Info Python 2.7 in IDLE
practical, answerable question based on actual problems that you face? (faq)in(therange(x)call in this case) is evaluated each time the loop is entered from above. Therefore, therangein the outer loop only gets evaluated once, but in the inner loop it gets evaluated for each iteration of the outer loop. Think ofrangeas returning a list, and what that list would hold, each time it is called. (In python2 it does return a list. In python3 it's more efficient, and returns arangetype that's like an iterator.)