pythonmatrixnested-for-loop

How can I display a nxn matrix depending on users input?


For a school task I need to display a nxn matrix depending on users input: heres an example:

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

(users input: 5)

And here is my code until now:

    n = int(input("please enter a number: "))

    for i in range( 1,n+1):
        for j in range(1,n+1):
            print(0, end = " ")
        print('\n')

So it only displays zero in my matrix, but how can I implement the one switching one position in each line?


Solution

  • n = int(input("please enter a number: "))
    
    for row_number in range(n):
        row = []
        for column_number in range(n):
            if row_number+column_number == n-1:
                row.append(1)
            else:
                row.append(0)
        print(*row)
    

    Output

    please enter a number: 5
    0 0 0 0 1
    0 0 0 1 0
    0 0 1 0 0
    0 1 0 0 0
    1 0 0 0 0