简体   繁体   中英

While loop inside for loop is not changing value of i of for loop in python 3.x

Here is my code

A = [0,0,-1,0]
for i in range(len(A)):
    while (i<len(A)) and (A[i] >=0):
        print(i, A[i]) 
        i=i+1

when I am executing this code in python 3.x my output is

Output

0 0
1 0
1 0
3 0

My question is : When while loop exits for the first time value of i becomes 2 since A[2] < 0

But after that when it goes to parent for loop then why value of i again becomes 1 ?

Because after that in 3rd line of output it prints 1 0 again.

Python for loops are not like C for loops; the iteration value is replaced on each loop, discarding any changes made inside the loop. No matter what you do to i inside the for loop, when the for loop loops, you pull the next value from the iterator, so i will always progress through all the values in the range one at a time.

The 'for' statement does not work like it might in C. The i variable gets reassigned each iteration.

You can think of 'for i in x' as being more like: while x has more values, set i to the next value from x.

The problem happens after the while loop exits. i is set to the next value in range(len(A)) which is 1 for the next iteration of the for loop.

You can fix this by initializing i and removing the for loop

A = [0,0,-1,0]
i=0
while (i<len(A)) and (A[i] >=0):
   print(i, A[i]) 
   i=i+1

Or using the break command

A = [0,0,-1,0]
for i in range(len(A)):
    if(A[i]<0):
        break
    print(i, A[i])

Try running the code in any Python debugger and you'll see it all at once. The code works correctly. If you need a specific result, ask, I will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM