Can you explain how the nested for loop behaves in figure 1?
x = 4
for j in range(x)
for i in range(x)
print(i)
x = 2
Fig.1
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
Thus showing that changing the value x inside the for loop has no impact on the number of iterations. The arguments in the range function are evaluated just before the first iteration of the loop, and not reevaluated for subsequent iterations.
Why then does x change to 2 for the nested loop in figure 1?
Another similar program:
num_list = [1, 2, 3]
alpha_list = ['a', 'b', 'c']
for number in num_list:
print(number)
for letter in alpha_list:
print(letter)
Outputs
1 #outer loop
a #nested loop
b #nested loop
c #nested loop
2 #outer loop
a #nested loop
b #nested loop
c #nested loop
3 #outer loop
a #nested loop
b #nested loop
c #nested loop
So I would expect figure 1's output to be:
0 #outer loop
0 #Nested loop
1 #Nested loop
2 #Nested loop
3 #Nested loop
1 #outer loop
0 #Nested loop
1 #Nested loop
2 #Nested loop
3 #Nested loop
2 #outer loop
0 #Nested loop
1 #Nested loop
2 #Nested loop
3 #Nested loop
3 #outer loop
0 #Nested loop
1 #Nested loop
2 #Nested loop
3 #Nested loop
Additional Info Python 3.5 in Spyder
Add some debug code to see what's going on to make it clearer
Output:
It's easy to see that setting
xonce the range is constructed has no affect on the number of outer loop iterations but does change the number of inner loop iterations.