- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Program to Print an Identity Matrix
When it is required to print an identity matrix, nested loops can be used.
Below is a demonstration for the same −
Example
n = 4 print("The value of n has been initialized to " +str(n)) for i in range(0,n): for j in range(0,n): if(i==j): print("1",sep=" ",end=" ") else: print("0",sep=" ",end=" ") print()
Output
The value of n has been initialized to 4 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1
Explanation
- The value of ‘n’ is initialized.
- A ‘for’ loop runs from 0 to ‘n’.
- Another nested ‘for’ loop runs from 0 to ‘n’ again.
- If the variables in the first and second ‘for’ loop are equal, then ‘1’ is printed.
- Otherwise, if they are not equal, then ‘0’ is printed on the console.
Advertisements