python for increment inner loop

前端 未结 5 1699
轻奢々
轻奢々 2020-12-09 10:07

How to increment the outer iterator from the inner loop?

To be more precise:

  for i in range(0,6):
    print i
    for j in range(0,5):
      i = i         


        
5条回答
  •  情深已故
    2020-12-09 10:54

    I read all the above answers and those are actually good.

    look at this code:

    for i in range(1, 4):
        print("Before change:", i)
        i = 20 # changing i variable
        print("After change:", i) # this line will always print 20
    

    When we execute above code the output is like below,

    Before Change: 1
    After change: 20
    Before Change: 2
    After change: 20
    Before Change: 3
    After change: 20
    

    in python for loop is not trying to increase i value. for loop is just assign values to i which we gave. Using range(4) what we are doing is we give the values to for loop which need assign to the i.

    You can use while loop instead of for loop to do same thing what you want,

    i = 0
    while i < 6:
        print(i)
        j = 0
        while j < 5:
            i += 2 # to increase `i` by 2
    

    This will give,

    0
    2
    4
    

    Thank you !

提交回复
热议问题