Take Matrix input from user in Python
Matrix is nothing but a rectangular arrangement of data or numbers. In other words, it is a rectangular array of data or numbers. The horizontal entries in a matrix are called as ‘rows’ while the vertical entries are called as ‘columns’. If a matrix has r number of rows and c number of columns then the order of matrix is given by r x c. Each entries in a matrix can be integer values, or floating values, or even it can be complex numbers.
Examples:
// 3 x 4 matrix
1 2 3 4
M = 4 5 6 7
6 7 8 9
// 2 x 3 matrix in Python
A = ( [ 2, 5, 7 ],
[ 4, 7, 9 ] )
// 3 x 4 matrix in Python where entries are floating numbers
B = ( [ 1.0, 3.5, 5.4, 7.9 ],
[ 9.0, 2.5, 4.2, 3.6 ],
[ 1.5, 3.2, 1.6, 6.5 ] )
In Python, we can take a user input matrix in different ways. Some of the methods for user input matrix in Python are shown below:
Code #1:
# A basic code for matrix input from user
R = int(input("Enter the number of rows:"))
C = int(input("Enter the number of columns:"))
# Initialize matrix
matrix = []
print("Enter the entries rowwise:")
# For user input
for i in range(R): # A for loop for row entries
a =[]
for j in range(C): # A for loop for column entries
a.append(int(input()))
matrix.append(a)
# For printing the matrix
for i in range(R):
for j in range(C):
print(matrix[i][j], end = " ")
print()
Output:
Enter the number of rows:2
Enter the number of columns:3
Enter the entries rowwise:
1
2
3
4
5
6
1 2 3
4 5 6
Time complexity: O(RC)
Auxiliary space: O(RC)
One liner:
# one-liner logic to take input for rows and columns
mat = [[int(input()) for x in range (C)] for y in range(R)]
Code #2: Using map() function and Numpy. In Python, there exists a popular library called NumPy. This library is a fundamental library for any scientific computation. It is also used for multidimensional arrays and as we know matrix is a rectangular array, we will use this library for user input matrix.
import numpy as np
R = int(input("Enter the number of rows:"))
C = int(input("Enter the number of columns:"))
print("Enter the entries in a single line (separated by space): ")
# User input of entries in a
# single line separated by space
entries = list(map(int, input().split()))
# For printing the matrix
matrix = np.array(entries).reshape(R, C)
print(matrix)
Output:
Enter the number of rows:2
Enter the number of columns:2
Enter the entries in a single line separated by space: 1 2 3 1
[[1 2]
[3 1]]
Time complexity: O(RC), as the code iterates through RC elements to create the matrix.
Auxiliary space: O(RC), as the code creates an RC sized matrix to store the entries.
Take Matrix input from user in Python – FAQs
How to Take Input Matrix from User in Python
To take an input matrix from a user in Python, you can use nested lists and take input using a loop. Here’s an example of how to take a matrix input from a user:
rows = int(input("Enter the number of rows: "))
cols = int(input("Enter the number of columns: "))
matrix = []
print("Enter the entries rowwise:")
for i in range(rows):
a =[]
for j in range(cols):
a.append(int(input()))
matrix.append(a)
print("The Matrix is:")
for i in range(rows):
for j in range(cols):
print(matrix[i][j], end = " ")
print()
How to Add Two Matrices in Python Using User Input
To add two matrices in Python using user input, you first need to take two matrices as input and then add them element-wise:
rows = int(input("Enter the number of rows: "))
cols = int(input("Enter the number of columns: "))
print("Enter the entries for the first matrix:")
matrix1 = [[int(input()) for x in range(cols)] for y in range(rows)]
print("Enter the entries for the second matrix:")
matrix2 = [[int(input()) for x in range(cols)] for y in range(rows)]
result = [[matrix1[i][j] + matrix2[i][j] for j in range(len(matrix1[0]))] for i in range(len(matrix1))]
print("Resultant Matrix:")
for r in result:
print(r)
How to Create a 3×3 Matrix in Python
Creating a 3×3 matrix in Python can be done using nested lists. Here’s a simple example:
matrix = [[0 for x in range(3)] for y in range(3)]
# Example of populating the matrix
for i in range(3):
for j in range(3):
matrix[i][j] = int(input(f"Enter element [{i}][{j}]: "))
print("3x3 Matrix:")
for row in matrix:
print(row)
How to Take Input from User in Python Pandas
In Python’s pandas, to take user input for creating a DataFrame, you might typically gather data using standard Python input techniques and then convert lists or dictionaries to DataFrame:
import pandas as pd
data = {
'Name': [],
'Age': []
}
n = int(input("Enter the number of entries: "))
for i in range(n):
name = input("Enter Name: ")
age = int(input("Enter Age: "))
data['Name'].append(name)
data['Age'].append(age)
df = pd.DataFrame(data)
print(df)
How Do You Take Input from User in Python Using Function
You can define a function to take user input more dynamically depending on the type of data you need:
def get_input(prompt, type_=str):
while True:
try:
return type_(input(prompt))
except ValueError:
print("Invalid input, try again.")
name = get_input("Enter your name: ")
age = get_input("Enter your age: ", int)
print(f"Name: {name}, Age: {age}")These examples cover a variety of ways to take user input in Python, from simple matrix input to more structured data input using pandas, suitable for different use cases in data handling and processing.