Home > OS >  Inverting of Boolean variable not happening after end of every for loop
Inverting of Boolean variable not happening after end of every for loop

Time:02-05

I am trying to create a pattern as follows -

1
0 1
1 0 1
0 1 0 1
1 0 1 0 1

My output is -

1
0 1
0 1 0
1 0 1 0
1 0 1 0 1

My code is as follows -

N=5
bool_ = True
for row in range(1,N 1):
    for i in range(1, row 1):
        if i>1:
            print(' ', end='')
        print(int(bool_), end= '')
        bool_ =  not bool_
    print()

Not sure what is wrong in this. It seems like something to do with range of second for loop.

CodePudding user response:

Sometimes the first character of a line is the same as the last character of the previous line, so the logic to always toggle the boolean will not work.

The int you could use is 1 - (row i) % 2:

    print(1 - (row   i) % 2, end= '')

You don't need the bool_ name for it.

  • Related