简体   繁体   中英

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM