print ("The scope of this program is to multiply two matrices together\
and print the result")


while True:
    matrix1_rows = input("How many rows does matrix one have? ")
    matrix1_columns = input("How many columns does matrix one have? ")

    print ("Matrix one is a", matrix1_rows, "x", matrix1_columns, "matrix")
    print()

    matrix2_rows = input("How many rows does matrix two have? ")
    matrix2_columns = input("How many columns does matrix one have? ")

    print ("Matrix two is a", matrix2_rows, "x", matrix2_columns, "matrix")

    if(matrix1_columns != matrix2_rows):
        print("\nSorry, cannot multiply these two matrices, must be (mxn)*(nxp)")


    else:
        break


print("----------------------------------------------------------")
print("\nThe system will now take values for matrix one, one row at a time")
print("Enter the values of the first row, click enter then the second row, and so on")

for i in range (0, int(matrix1_rows)):

        if (i == 0):
            matrix1_row1_set = input("Please enter the values for the row\n")

I want to be able to have the user enter the number of rows that the matrix has and then ask for each rows value (Like user entering "1 0 5 9 5") and assigning that to the variable matrix1_row1_set then getting another row and assigning it to a variable like matrix1_row2_set

What would be the most efficient way to do this?

The most efficient way is to append the rows one at a time to a list:

...
matrix1_rows = input(...)
matrix1_rows = int(matrix1_rows)
...
matrix1 = []

for i in range(matrix1_rows):
    ... input ...
    row = ...
    matrix1.append(row)

after this loop, the rows will be matrix1[0], matrix1[1],... up to matrix1[1matrix1_rows - 1].

Edited 2 Years Ago by Gribouillis

That sounds so smart, I talked to my prof and he suggested the same kind of thing. Just without hard code in the example. Thanks!

You might like to also try data entry something like this:

# takeInMatrix.py #


def takeInRow( numCols ):
    data = input( "Enter "+str(numCols)+" numbers separated by a space: ")
    items = data.split()

    good = True
    cols = []
    for item in items:
        try:
            num = float(item)
            cols.append( num )
        except:
            print( "There was some invalid data ... " )
            good = False
    return good, cols




def takeInMatrix( rows, cols ):
    matrix = []
    i = 0
    while i < rows:
        good, row = takeInRow( cols )
        if good:
            if len(row) == cols:
                matrix.append( row )
                i += 1
            else:
                print( "\nMust be", cols, "numbers entered ..\n" )
        else:
            print( "Try again ... " )

    return matrix



mat = takeInMatrix( 3, 5 )

for row in mat:
    print( row )

Edited 2 Years Ago by David W

This article has been dead for over six months. Start a new discussion instead.