Search code examples
pythonbreak

The first non-zero element in each row


import numpy as np
a=np.array([[0,0,0],
      [1,2,0],
      [0,2,1],
      [0,1,2],
      [2,1,3],
      [0,0,0]])
for i in range(6):
  for j in range(3):
    if a[i,j]!=0:
      print(i+1,'-th row,',j+1,'-th column','\nthe 1st non-zero element:',a[i,j],'\n---')
    break

enter image description here

I think the problem caused by break, but have no idea how to deal with it.

Thanks in advance!


Solution

  • If I understood correctly, the break should be inside the if statement

    if a[i,j]!=0:
          print(i+1,'-th row,',j+1,'-th column','\nthe 1st non-zero element:',a[i,j],'\n---')
          break