How to Print Identity Matrix of a Number in Python


In this example, we will learn how to print an identity matrix of a given number in Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

n = int(input("Please input a number: "))
for i in range(n):
    for j in range(n):
        if i == j:
            print("1", sep=" ", end=" ")
        else:
            print("0", sep=" ", end=" ")
    print()

Output:

Please input a number: 6
1 0 0 0 0 0
0 1 0 0 0 0
0 0 1 0 0 0
0 0 0 1 0 0
0 0 0 0 1 0
0 0 0 0 0 1
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement