Python nested in loop behavior

I came across this weird behavior with nested loops and I can't explain what this explains to me. Is it specific to python or am I just watching something?

This is the code I'm running:

for i in range(16): if i == 0: for j in range(8): print 'i is (if) ' + str(i) i = i + 1 else: print 'i is (else)' + str(i) 

This is the result I get:

 i is (if) 0 i is (if) 1 i is (if) 2 i is (if) 3 i is (if) 4 i is (if) 5 i is (if) 6 i is (if) 7 i is (else)1 i is (else)2 i is (else)3 i is (else)4 i is (else)5 i is (else)6 i is (else)7 i is (else)8 i is (else)9 i is (else)10 i is (else)11 i is (else)12 i is (else)13 i is (else)14 i is (else)15 

This is the result that I expect:

 i is (if) 0 i is (if) 1 i is (if) 2 i is (if) 3 i is (if) 4 i is (if) 5 i is (if) 6 i is (if) 7 i is (else)8 i is (else)9 i is (else)10 i is (else)11 i is (else)12 i is (else)13 i is (else)14 i is (else)15 

It seems that I am in the outer loop, and I in the inner loop are different variables, although this seems completely uninteresting to me.

Any input (I'm pretty new to python, but can't find documentation on this)

+4
source share
1 answer

The for loop assigns a new value i each iteration of the loop, namely the next value taken from the iterable loop (in this case, range(16) .

You can change i in the loop itself, but that will not change the iterative for .

If you want to change the iterable loop, then you will need to do it directly on iterable:

 loop_iterable = iter(range(16)) for i in loop_iterable: if i == 0: for j in range(8): print 'i is (if) ' + str(i) i = next(loop_iterable) else: print 'i is (else)' + str(i) 

Here we create an iterator object from the range(10) sequence using iter() ; the for statement does the same under the hood, but now we can directly access the iterator. The next() function advances the iterator to the next value, as a for loop would do.

However, the easiest way is to use a while :

 i = 0 while i < 16: if i == 0: for j in range(8): print 'i is (if) ' + str(i) i = next(loop_iterable) else: print 'i is (else)' + str(i) i += 1 

Keep in mind that the Python for loop statement is not like a C loop or Java or JavaScript for loop. Instead, it is a Foreach loop . range() simply generates a sequence of numbers for the loop, as opposed to a C-style for loop, which combines the initial assignment ( i = 0 ), test ( i < 16) ) and the loop increment ( i += 1 ) into one statement.

+8
source

Source: https://habr.com/ru/post/1495775/


All Articles