This is a Python Program to read a number n and print an identity matrix of the desired size.
The program takes a number n and prints an identity matrix of the desired size.
1. Take a value from the user and store it in a variable n.
2. Use two for loop where the value of j ranges between the values of 0 and n-1 and value of i also ranges between 0 and n-1.
3. Print the value of 1 when i is equal to j and 0 otherwise.
4. Exit.
Here is the source code of the Python Program to read a number n and print an identity matrix of the desired size. The program output is also shown below.
n=int(input("Enter a number: ")) 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()
1. User must first enter the value and store it in a variable n.
2. The outer for loop enables j to range between 1 and n-1 (as n is not included) while the inner for loop also enables i to range between 1 and n-1.
3. For each iteration, the value of 1 is printed if i is equal to j and value of 0 is printed otherwise.
4. The sep and end parameters of the print function help in formatting and print() allows values to printed in a new line for each iteration of the outer for loop.
Case 1: Enter a number: 4 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 Case 2: Enter a number: 5 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1
Sanfoundry Global Education & Learning Series – Python Programs.
To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.
- Check Information Technology Books
- Apply for Python Internship
- Practice Programming MCQs
- Apply for Programming Internship
- Check Python Books