Search code examples
pythonpython-3.xmatrixuser-input

Taking 'n' space separated integers in Python, storing in matrix and print the matrix


I want to take n space separated integers and storing in a matrix and then print the matrix. I am using Python 3.7.

My code is:


size = int(input("\nEnter number of rows or colums: ")) #square matrix

#Define the matrix
matrix = []
print("\nEnter the entries:")

#for user input
for row in range(size):     
    temp = []
    for column in range(size):      
        temp.append(int(input()))
    matrix.append(temp)


#To print the matrix
print("\nThe matrix is :")
for i in range(size):
    for j in range(size):
        print(matrix[i][j], end="\t")
    print()

I can only able to take input like this

Enter number of rows or colums: 2

Enter the entries:
1
2
3
4

The matrix is :
1       2
3       4

but I want to take input like this

Enter number of rows or colums: 2

Enter the entries:
1 2
3 4

The matrix is :
1       2
3       4

If I try to take space separated integers and then press Enter for the new line I get this below error massage

Enter number of rows or colums: 2

Enter the entries:
1 2
Traceback (most recent call last):
  File "e:/Python/matrix.py", line 12, in <module>
    temp.append(int(input()))
ValueError: invalid literal for int() with base 10: '1 2'

Can anyone help me? Thanks in advance.


Solution

  • Here is the updated code:

    size = int(input("\nEnter number of rows or colums: ")) #square matrix
    
    #Define the matrix
    matrix = []
    print("\nEnter the entries:")
    
    #for user input
    for row in range(size):
        # Read row, space separated value
        matrix.append(
            [int(n) for n in input().split(' ')]
        )
    
    #To print the matrix
    print("\nThe matrix is :")
    for i in range(size):
        for j in range(size):
            print(matrix[i][j], end="\t")
        print()