1

I am learning Python and I came across something with the for loop.

Let's say I have a program that asks for 5 numbers. (I know it's pointless but it's good for an example.) Anyways, if I do this, it won't restart its cycle:

myNumbers = []
for x in xrange(5):
    try:
        myNumbers.append( int(raw_input()) )
    except ValueError:
        myNumbers = []
        x = -1

I thought if I had reset x to -1 it would just make the for loop go on even more, but it never restarted. It still only went 5 times. The reason why I put -1 there is because x would count back up to 0 right after that. I tried to find solutions, but there weren't any. Thank you for helping me.

Olivia Stork
  • 4,660
  • 5
  • 27
  • 40
fu_______
  • 11
  • 6

1 Answers1

2

xrange() (or range() ) are called generator functions, x is like the local variable that the for loop assigns the next value in the loop to.

xrange() returns the values in the range given in parameters 1 by 1 , and for loop assigns that to the variable x. So even if you change the value of x within the loop, xrange() has no idea about such a change and would still provide the next value in the range.

Example of generator functions -

def myrange(a):
    i = 0
    while i < a:
        yield i
        i = i + 1

>>> for x in  myrange(10):
...     print(x)
...     x = 1
...
0
1
2
3
4
5
6
7
8
9

The value change in x is never propagated back to the range() or xrange() function.

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176