Home > Software design >  Value of i in loop keeps getting overridden even after changing explicitly
Value of i in loop keeps getting overridden even after changing explicitly

Time:10-10

This code is for reference. Working on a code with a similar implementation. I wanted to override the value of i inside the loop:

def function():
    num = 10
    for i in range(num):
        print(i)
        if (i % 2 == 0):
            i = i   2
        else:
            i = i   1

The actual output fro the above code : 0 1 2 3 4 5 6 7 8 9

I expected that the value of i will be updated inside the loop, since I have different values to add to i depending on the condition, whereas it was getting overridden at the start of the loop to be in sequence. Can anyone explain how can i stop this? I wanted to update the value of i inside the loop logic.

CodePudding user response:

In Python, your loop variable keeps getting reinitialized. If you want to run a loop without getting the variable reinitialized, you have to use while loop.

def function():
    num = 10
    i = 0
    while i < num:
        print(i)
        if (i % 2 == 0):
            i = i   2
        else:
            i = i   1

CodePudding user response:

In for loop, once the variable is decided, the value doesn't change, ot changes only based on the updating value of range. You can change the value only in case of while loop. Try using while loop. Use this:

while i<10: #num

      print(i)

     if i%2==0:

          i =2

      else:

          i =1

Check for indentation errors, I've written it on my own

  • Related