Introduction
A matrix is a two-dimensional array of numbers arranged in rows and columns. In Python, you can create and display a matrix using lists of lists. This guide will walk you through creating a Python program to display a matrix. We’ll explain the code, how to run it, and how to understand the output.
Python Code to Display a Matrix
# Function to display a matrix
def display_matrix(matrix):
for row in matrix:
for element in row:
print(element, end=" ")
print() # Newline after each row
# Main function
def main():
# Define a matrix (2D list)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Display the matrix
print("The matrix is:")
display_matrix(matrix)
# Run the main function
if __name__ == "__main__":
main()
PythonExplanation of the Code
- Defining the Matrix:
- The matrix is defined as a list of lists in Python. Each inner list represents a row of the matrix. In the example code, the matrix is defined as:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
PythonThis creates a 3×3 matrix where the numbers 1 to 9 are arranged in a grid.
Displaying the Matrix:
- The
display_matrix()
function is designed to take a matrix as input and print it row by row. - The outer
for
loop iterates through each row in the matrix. - The inner
for
loop iterates through each element in the row and prints it on the same line, separated by a space. - After printing each row, a
print()
statement is used to move to the next line, ensuring the matrix is displayed correctly.
Main Function:
- The
main()
function is where the matrix is defined and thedisplay_matrix()
function is called. - The
if __name__ == "__main__":
statement ensures that themain()
function is run only when the script is executed directly, not when it’s imported as a module.
Running the Code:
- Save the code in a file, for example,
display_matrix.py
. - Run the script in a Python environment or terminal using the command.
python display_matrix.py
PythonOutput
The matrix is:
1 2 3
4 5 6
7 8 9
PythonHow Output is Displayed
The display_matrix()
function prints each row of the matrix on a new line.
The numbers within each row are separated by a space.
The output format reflects the structure of the matrix, making it easy to visualize the 2D grid.