-1

I want to modify variable y and it works in Java as below

for(int x=0;x<4;x++)
          {
            for(int y=0;y<3;y++)
            {
                System.out.print(y);
                if(y==1){y+=1;}              
            } 
          } // output == 01010101

But when I try to implement the same logic in Python it doesn't work as below

for x in range(0,4):
    for y in range(0,3):
        print(y, end='')
        if y==1:
            y+=1 # output == 012012012012

is there way to modify a variable in inner for-range loop in python?

Ke.N
  • 19
  • 5
  • You should note that it is considered bad practice to change the value of the iterator (in this case, `y`) inside the for loop. – Mikhail Genkin Mar 18 '21 at 13:38
  • In a `for` loop, IMHO the loop variable should only be increased in the `for` part, not in the body. It makes the code hard to understand. – Robert Mar 18 '21 at 13:39
  • For more read [The for statement in Python differs a bit from what you may be used to in C (and Java)](https://docs.python.org/2/tutorial/controlflow.html#for-statements). – jarmod Mar 18 '21 at 13:40

1 Answers1

-1

This is the code which is working, just change the range of y from (0, 3) to (0, 2):

for x in range (0, 4):
    for y in range (0, 2):
        print(y, end = '')
        if y == 1:
            y += 1
Devansh Singh
  • 134
  • 1
  • 10