I’m new to python coding and i dont understand why the nested for loop is only returning 0 1 2 for the firs Iteration.
Input:
x = 3
for i in range (x):
for j in range (x):
x = 2
print (i, '',j)
Output:
0 0
0 1
0 2
1 0
1 1
2 0
2 1
CodePudding user response:
x
is changed after it's passed to range
to make range(3)
. You only see the effects of the change (i.e. range(2)
) on the next loop.
CodePudding user response:
Long version
range
is not a 'reserved' word; it is the name of a built-in type(class). Note : The syntax highlighter cheats when it highlights range
as a reserved word. It does this, because this is generally useful as range
is mainly used in association with for
. But this does not change what range is. However, this can mislead you
As a result of the above, the correct typing is range(x)
not range (x)
range(x)
build an objet of type range and initialize it with x
.
Short answer
x
is interpreted when it is passed to range()
.
Code to print the range objects:
x = 3
range_i = range(x)
print(f"i loop x: {x}, range(x):{range_i}")
for i in range_i:
range_j = range(x)
print(f"j loop x: {x}, range(x):{range_j}")
for j in range_j:
x = 2
print (i, ' ',j)
Output
i loop x: 3, range(x):range(0, 3)
j loop x: 3, range(x):range(0, 3)
0 0
0 1
0 2
j loop x: 2, range(x):range(0, 2)
1 0
1 1
j loop x: 2, range(x):range(0, 2)
2 0
2 1
Musing around
Note : what follows is NOT recommended
You can redefine range. (The example below is a very simplified redefinition: it does not take in account the second version of range : range(start, stop[, step]
) neither it cares for other range
specifications)
def range(n):
i = 0
while i <= n: # note the use of '<=' instead of '<'
yield i
i = 1
And now 'range' does not behave as it should. Example:
for i in range(3):
print(i)
gives:
0
1
2
3
Yes 0..3 not 0..2 as the 'true' range
.