Sunday, 22 December 2024

Day 52: Python Program to Print an Identity Matrix


 def print_identity_matrix(n):

    """

    Prints an identity matrix of size n x n.

    :param n: Size of the identity matrix

    """

    if n <= 0:

        print("Please enter a positive integer for the size of the matrix.")

        return

for i in range(n):

        for j in range(n):

            if i == j:

                print(1, end=" ")

            else:

                print(0, end=" ")

        print()  

try:

    size = int(input("Enter the size of the identity matrix: "))

    print_identity_matrix(size)

except ValueError:

    print("Invalid input! Please enter a valid integer.")

#source code --> clcoding.com

Code Explanation:

1. Function Definition:
def print_identity_matrix(n):
    """
    Prints an identity matrix of size n x n.
    :param n: Size of the identity matrix
    """
print_identity_matrix(n): This function takes one argument, n, which represents the size of the identity matrix.
The identity matrix is a square matrix where all diagonal elements are 1, and all other elements are 0.

2. Input Validation:
if n <= 0:
    print("Please enter a positive integer for the size of the matrix.")
    return
If the user provides a non-positive integer (n <= 0), the function outputs a warning message and stops further execution using return.

3. Nested Loop to Generate the Matrix:
for i in range(n):
    for j in range(n):
        if i == j:
            print(1, end=" ")
        else:
            print(0, end=" ")
    print()
Outer Loop (for i in range(n)):
Iterates over the rows of the matrix.
Inner Loop (for j in range(n)):
Iterates over the columns of the matrix.
Condition (if i == j):
Checks if the current position (i, j) is a diagonal element. If true, it prints 1; otherwise, it prints 0.
print(..., end=" "):
Ensures that elements in the same row are printed on the same line with a space in between.
print() (outside inner loop):
Moves to the next line after completing each row.

4. User Input and Error Handling:
try:
    size = int(input("Enter the size of the identity matrix: "))
    print_identity_matrix(size)
except ValueError:
    print("Invalid input! Please enter a valid integer.")
input(): Prompts the user to enter the size of the identity matrix.
int(input(...)): Converts the user's input to an integer.
try-except Block: Catches invalid inputs (e.g., non-integer values) and displays an error message.

5. Example Execution:
Input:
Enter the size of the identity matrix: 3

Output:
1 0 0 
0 1 0 
0 0 1 

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (56) AI (34) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (174) C (77) C# (12) C++ (82) Course (67) Coursera (228) Cybersecurity (24) data management (11) Data Science (128) Data Strucures (8) Deep Learning (21) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (60) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (3) Pandas (4) PHP (20) Projects (29) Python (935) Python Coding Challenge (368) Python Quiz (27) Python Tips (2) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (4) Software (17) SQL (42) UX Research (1) web application (8) Web development (4) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses