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?

Dani AI

Generated

A few practical points that build on and without reusing their exact snippets.

Treat a matrix as a list of rows (a list of lists) rather than trying to create dynamic variable names like matrix1_row1_set. Convert the dimension inputs to integers up front, fix the small prompt typo in the original code (the second prompt asks about "matrix one" again), and check shape compatibility with numeric values (e.g. if matrix1_cols != matrix2_rows: only after you cast to int).

Keep input parsing simple and robust: accept spaces or commas, strip extra whitespace, convert each token to int or float, verify the number of values matches the expected column count, and re-prompt on error. Avoid eval/exec or generating variable names at runtime — they make code brittle and unsafe.

An example pattern (different from earlier posts) that is compact and easy to reuse:

def read_matrix(rows, cols, prompt="Enter row"):
    mat = []
    for r in range(rows):
        while True:
            line = input(prompt + " {}: ".format(r+1))
            try:
                nums = [float(x) for x in line.replace(',', ' ').split()]
            except ValueError:
                print("Non-numeric value — try again.")
                continue
            if len(nums) != cols:
                print("Expected {} values, got {}.".format(cols, len(nums)))
                continue
            mat.append(nums)
            break
    return mat

After both matrices are read into lists, either implement the usual triple-loop matrix multiply or convert to NumPy arrays (import numpy as np; A = np.array(mat1); B = np.array(mat2); C = A.dot(B)) for correctness and performance. Troubleshooting checklist: ensure you cast dimensions to integers, validate each input row length, handle stray commas/extra spaces, and test with a small 2x2 example to confirm multiplication code before scaling up.

Recommended Answers

All 3 Replies

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].

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 )
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.