# python - matrices program asking for user input

``# 3x3X = [[0,0,0],[0 ,5,6],[7 ,0,0]]# 3x4Y = [[0,0,0,0],[0,0,0,0],[0,0,0,0]]# 3x4result = [[0,0,0,0],[0,0,0,0],[0,0,0,0]]# iterate through rows of Xfor i in range(len(X)):# iterate through columns of Yfor j in range(len(Y)):# iterate through rows of Yfor k in range(len(Y)):result[i][j] += X[i][k] * Y[k][j]#This code multiplies matrices X and Y and puts the resulting product into matrix result#It then prints the matrix result row by row, so it looks like a matrix on the screenfor r in result:print(r)``

here i have a program that will work out a matrix but i was wondering on how to ask the user for the input when running the program instead of inputting the numbers beforehand

A particularly easy way to get two matrices from the user is to use the function `literal_eval` from the module ast:

``````import ast
X = ast.literal_eval(input("Enter the first matrix as a list of lists: "))
Y = ast.literal_eval(input("Enter the second matrix: "))
#code to compute X*Y -- note that you can't hard-wire the size of result
``````

The beauty of this approach is that if the user enters `[[1,2],[3,4]]` at the prompt (which yields the string `'[[1,2],[3,4]]'`) then `literal_eval` converts this string to the list `[[1,2],[3,4]]`.

To make this approach robust you should use error-trapping to gracefully handle situations where the user e.g. enters `[[1,2][3,4]]` by mistake.

As far as not hard-wiring in the size of `result`: Since the product is filled in row by row, I recommend refactoring your code by initializing `result` as an empty list to which rows are appended as they are calculated. As a template something like:

``````result = []
for i in range(len(X)):
row = *len(Y)
for j in range(len(Y)):
# code to compute the jth element of row i
result.append(row)
``````