Can anyone tell why do I get an infinite loop? While-loop

Question:

I wanna replace 1 to * and 0 to ” to make a tree.
I did this with for-loop.

picture = [
  [0,0,0,1,0,0,0],
  [0,0,1,1,1,0,0],
  [0,1,1,1,1,1,0],
  [1,1,1,1,1,1,1],
  [0,0,0,1,0,0,0],
  [0,0,0,1,0,0,0]
]
i = 0
while i < len(picture):
    j = 0
    while j < len(picture[i]):
        if picture[i][j] == 0:
            print('', end='')
        else:
            print('*', end='')
    i += 1
Asked By: Super Human

||

Answers:

You are not incrementing j in your second while loop.

picture = [
  [0,0,0,1,0,0,0],
  [0,0,1,1,1,0,0],
  [0,1,1,1,1,1,0],
  [1,1,1,1,1,1,1],
  [0,0,0,1,0,0,0],
  [0,0,0,1,0,0,0]
]
i = 0
while i < len(picture):
    j = 0
    # in this while loop j is never incremented which means it stays as the value 0
    while j < len(picture[i]): 
        if picture[i][j] == 0:
            print('', end='')
        else:
            print('*', end='')
        j += 1 # Add J += 1 here
    i += 1
Answered By: Matt Seymour

try this.

picture = [
  [0,0,0,1,0,0,0],
  [0,0,1,1,1,0,0],
  [0,1,1,1,1,1,0],
  [1,1,1,1,1,1,1],
  [0,0,0,1,0,0,0],
  [0,0,0,1,0,0,0]
]
i = 0
while i < len(picture):
    j = 0
    while j < len(picture[i]):
        if picture[i][j] == 0:
            print('', end='')
        else:
            print('*', end='')
        j += 1
    print()
    i += 1

If you want this output

*
***
*****
*******
*
*
Answered By: japan
while i < len(picture):
j = 0
while j < len(picture[i]):
    if picture[i][j] == 0:
        print(' ', end='')
        j += 1
    else:
        print('*', end='')
        j += 1
print('')
i += 1
Answered By: Super Human
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.