Python Program to Print Square With Diagonal Numbers Pattern

Write a Python program to print the square with all zeros except the pattern of the diagonal numbers using for loop.

rows = int(input("Enter Square With Diagonal Numbers Rows = "))

print("====The Square With Diagonal Numbers and Remaining 0's Pattern====")

for i in range(1, rows + 1):
    for j in range(1, i):
        print('0', end = ' ')
    print(i, end = ' ')
    for k in range(i, rows):
        print('0', end = ' ')
    print()
Python Program to Print Square With Diagonal Numbers Pattern

It is another way of printing the square pattern with diagonal numbers and all the remaining zeros in Python. For more patterns, please refer to the Python Number pattern programs.

rows = int(input("Enter Square With Diagonal Numbers Rows = "))

print("====The Square With Diagonal Numbers and Remaining 0's Pattern====")

for i in range(1, rows + 1):
    for j in range(1, rows + 1):
        if i == j:
            print(i, end = ' ')
        else:
            print('0', end = ' ')
    print()
Enter Square With Diagonal Numbers Rows = 8
====The Square With Diagonal Numbers and Remaining 0's Pattern====
1 0 0 0 0 0 0 0 
0 2 0 0 0 0 0 0 
0 0 3 0 0 0 0 0 
0 0 0 4 0 0 0 0 
0 0 0 0 5 0 0 0 
0 0 0 0 0 6 0 0 
0 0 0 0 0 0 7 0 
0 0 0 0 0 0 0 8 

This Python program displays the square pattern of incremental diagonal numbers. All the remaining ones are zeros using a while loop.

rows = int(input("Enter Square With Diagonal Numbers Rows = "))

print("====The Square With Diagonal Numbers and Remaining 0's Pattern====")
i = 1

while(i <= rows):
    j = 1
    while(j <= rows):
        if i == j:
            print(i, end = ' ')
        else:
            print('0', end = ' ')
        j = j + 1
    print()
    i = i + 1
Enter Square With Diagonal Numbers Rows = 9
====The Square With Diagonal Numbers and Remaining 0's Pattern====
1 0 0 0 0 0 0 0 0 
0 2 0 0 0 0 0 0 0 
0 0 3 0 0 0 0 0 0 
0 0 0 4 0 0 0 0 0 
0 0 0 0 5 0 0 0 0 
0 0 0 0 0 6 0 0 0 
0 0 0 0 0 0 7 0 0 
0 0 0 0 0 0 0 8 0 
0 0 0 0 0 0 0 0 9 

Also Read