I have a code:
x = 6
for y in range(x):
print(y)
x -= 2
It gives: 0, 1, 2, 3, 4, 5
I wrongly predicted that it would give either of these 2 results:
0, 0, 0
Sincex
goes from 6 to 4 to 2 to 0, there will only be 3y
printed. Also, to my understanding, after each loop, it goes back to the for loop statement, thus resets the range() completely and now everyy
is 0. I ran the code on PythonTutor and the pointer also seemed to go back to the loop statement after each loop.0, 1, 2
Sincex
goes from 6 to 4 to 2 to 0, there will only be 3y
printed. I thought it might be possible that while y takes on the value of the original range (i.e. 6), it would be limited by each newx
and thus only have 3y
printed.
Possibility 1 was the most intuitive (albeit wrong) for me and I am not sure how to go about understanding why the answer is as such.
CodePudding user response:
The instance of range
produced by range(x)
uses the value of x
at the time range
is called. It does not repeatedly check the value of x
each time you need a new value from the range. Your code is effectively the same as
x = 6
for y in [0, 1, 2, 3, 4, 5]:
print(y)
x -= 2
Nothing you do to x
has any effect on the range
object being iterated.
CodePudding user response:
The range()
call creates a range
object from x
at the start of the loop. Changing x
after this has no effect on the range
object that is being used to iterate.
If you want to be able to change how many iterations you make in a loop, you probably want to look at using while
.
CodePudding user response:
Try this:
# Firstly you assign 6 to the variable x
x = 6
# 'y' will now be assigned to the numbers [0, 1, 2, 3, 4, 5, 6] because the range is 'x' which is 6.
# by printing 'x' it will execute [0, 1, 2, 3, 4, 5, 6] but since x is 'x -2' which is the same as '6 - 2' it will print out the number 6 and -2 until it gets to the range which is -6. the output will be 6 numbers [6, 4, 2, 0, -2, -4]
for y in range(x):
print(x)
x = x - 2
# i am showing you a way of making it give you your expected output [6, 4, 2, 0, -2, -4]