Introduction
Program To Display 3*3 Matrix
In this guide, we’ll learn how to create and display a 3×3 matrix in Python program . A matrix is simply a collection of numbers arranged in rows and columns, like a grid. Here, we’ll use Python lists to represent our matrix and print it out in a neat format.
Python Program to Display a 3×3 Matrix
# Function to display a 3x3 matrix
def display_matrix(matrix):
for row in matrix:
for element in row:
print(element, end=" ")
print() # Move to the next line after each row
# Main function to run the program
def main():
# Define a 3x3 matrix
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Display the matrix
print("Here is the 3x3 matrix:")
display_matrix(matrix)
# Execute the main function
if __name__ == "__main__":
main()
PythonSteps Explained
We create a 3×3 matrix by using a list of lists.
Each small list represents a row of the matrix. In the code, the matrix looks like this:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Python-
Displaying the Matrix
-
Program:
-
The
display_matrix()
function is responsible for printing the matrix. -
We use two loops: the first loop goes through each row, and the second loop goes through each element in that row.
-
print(element, end=" ")
prints each number on the same line with a space in between. -
After printing all elements in a row,
print()
moves to the next line, so each row appears on a new line.
-
-
Running the Program:
-
The
main()
function is where the matrix is defined and then displayed. -
The line
if __name__ == "__main__":
ensures the program runs when you execute the script.
-
Output
When you run the code, you’ll see this output:
Here is the 3x3 matrix:
1 2 3
4 5 6
7 8 9
PythonConclusion
This simple program shows how to create and display a 3×3 matrix in Python. By following these steps, you can understand how matrices work and how to manipulate and display them using basic Python code. This is a foundational concept that you can build upon as you learn more about programming and working with data.
- Python.org
- The official Python website offers a comprehensive tutorial that covers everything from basic syntax to advanced topics.
- W3Schools – Python Tutorial
- W3Schools provides an easy-to-follow Python tutorial with examples, quizzes, and interactive coding exercises.
- GeeksforGeeks – Python Programming Language
- GeeksforGeeks offers detailed articles, examples, and problem-solving challenges that cover Python programming comprehensively.
- Real Python
- Real Python offers in-depth tutorials, video courses, and a community of Python developers to help you learn Python effectively.
- Codecademy – Learn Python
- Codecademy provides an interactive learning platform with hands-on coding exercises and projects to help you learn Python.
These websites provide a range of resources suitable for beginners to advanced learners, helping you master Python programming.