I've just started learning Python and after few lessons I grasped the idea of lists and loop and decided to create my first project.

Objective: Calculate multiplication of any two matrices from user's input.

The code is working as intended but as this is my first one, I would be happy for some hints as far what is written well and what is e.g. hard to read by someone, wrongly used method or unnecessary complication.

I specifically wanted to stay within basic knowledge and not use for example NumPy for learning reason. There will be time for libraries in future.

Thanks all in advance and my code is below:

# This program multiplicates two matrices of any number of rows and columns.
# The matrix elements are filled by User
# The result is calculated and saved as list


# Ask user for dimensions of first matrix
r = int(input("Matrix1: Number of rows?: "))
c = int(input("Matrix1: Number of columns?: "))

# Print design of first Matrix for better understanding of elements' naming convention
print('''\nElements of matrix1:''')
element = ''                            # Later will be used to construct each row of the matrix
for vr in range(0, r):                  # vr - variable row
    for vc in range(0, c):              # vc - variable column
        element += 'M' + str(vr + 1) + str(vc + 1) + ' '
    print('|', element, '\b|')
    element = ''

# Create empty Matrix1 and fill it with user input element by element
Matrix1 = [[] for vr in range(0, r)]
for vr in range(0, r):
    Matrix1[vr] = [0 for vc in range(0, c)]

for vr in range(0, r):
    for vc in range(0, c):
        Matrix1[vr][vc] = int(input('M' + str(vr + 1) + str(vc + 1) + ': '))    # + 1 because vr and vc starts at 0 and we want elements be named from 1

# Ask the user for dimension of second matrix
v = int(input("Matrix2: Number of columns?: "))     # Only for columns since M2 rows = M1 columns by definition
print('''\nElements of matrix Matrix2:''')
element = ''
for vr in range(0, c):                  # vr in c because Matrix 2 must have the same number of rows as Matrix1 columns.
    for vc in range(0, v):
        element += 'M' + str(vr + 1) + str(vc + 1) + ' '
    print('|', element, '\b|')
    element = ''

# Create Empty Matrix2 and fill it with user input element by element
Matrix2 = [[] for vr in range(0, c)]
for vr in range(0, c):
    Matrix2[vr] = [0 for vc in range(0, v)]

for vr in range(0, c):
    for vc in range(0, v):
        Matrix2[vr][vc] = int(input('M' + str(vr + 1) + str(vc + 1) + ': '))

# Create empty Product Matrix for Result of multiplication of Matrix1 and Matrix2
Product = [[] for vr in range(0, r)]                # Number of rows defined by number of rows in Matrix1
for vr in range(0, r):
    Product[vr] = [0 for columns in range(v)]       # Number of columns defined by number of columns in Matrix2

# Calculate the Product of two tables
Products = 0            # dummy variable for calculating sum of product of each row and column
for vv in range(0, v):
    for vr in range(0, r):
        for vc in range(0, c):
            Products += Matrix1[vr][vc] * Matrix2[vc][vv]
        Product[vr][vv] = Products
        Products = 0        # clear the variable when looped for whole column of Matrix2

print('Matrix1: ', Matrix1)
print('Matrix2: ', Matrix2)
print('Result of Matrix Multiplication:', Product)

# Footnotes
print('\n\nCreated by: MK')
input('Press "Enter" to Exit')        # Easy way to Exit program If run from script
  • \$\begingroup\$ Don't use lists for numerical calculations if you don't have to. There are only some rare cases, where using lists in numerical calculations is feasable. So, a nice learning example would be to programm a matrix multiplication which beats numpy.dot in small matrices, but using ndim arrays provided by numpy... \$\endgroup\$
    – max9111
    Feb 8, 2018 at 9:06

3 Answers 3


I have basically two comments:

  1. Naming.
  2. Use functions to follow the single responsibility principle.


Python has an official style-guide, PEP8. Some of its recommendations are:

  • Using lower_case for variables and functions, PascalCase for classes and ALL_CAPS for global constants.
  • To limit your line length to 80 (or at the most 120) characters

Your names which you use to iterate through the rows and columns are not clear at all. Why vc and vr (I guess the c and r stand for column and row, but what does the v stand for?)? Instead I would use rows and columns for the number of rows and columns and use i and j to iterate over them, because that is the convention used in mathematics when describing matrices.

Single responsibility principle

As for your actual code, you basically have four major responsibilities:

  1. Asking the user for input
  2. Creating a matrix
  3. Calculating the matrix product
  4. Printing a matrix scheme

I would make this into four functions:

def ask_user(message):
    while True:
            return int(input(message))
        except TypeError:

This function will ask the user the message until he inputs something that can be cast to an int.

def matrix_from_user():
    rows = ask_user("Number of rows?: ")
    columns = ask_user("Number of columns?: ")
    matrix = [[0] * columns for _ in range(rows)]
    for i in range(rows):
        for j in range(columns):
            matrix[i][j] = ask_user("M{}{}: ".format(i+1, j+1))
    return matrix

Here I used str.format to make the construction of the string easier.

def matrix_mul(matrix1, matrix2):
    rows, columns = len(matrix1), len(matrix2[0])
    matrix = [[0] * columns for _ in range(rows)]
    for i in range(rows):
        for j in range(columns):
            matrix[i][j] = sum(matrix1[i][k] * matrix2[k][j]
                               for k in range(len(matrix2)))
    return matrix

This is a straightforward implementation of the formula \$(AB)_{ij} = \sum_{k=1}^m A_{ik} B_{kj}\$ for two matrices \$A\$ and \$B\$. It uses the built-in sum function that takes an iterable to sum. This iterable is a generator comprehension here.

def matrix_print(matrix):
    print('\nElements of matrix:')
    rows, columns = len(matrix), len(matrix[0])
    for i in range(rows):
        row = ' '.join('M{}{}'.format(i + 1, j + 1) for j in range(columns))
        print('|', row, '|')

Here I used str.join to easily join an iterable of strings with a given delimiter (' ' here).

Your main program becomes then simply:

if __name__ == "__main__":
    matrix1 = matrix_from_user()
    matrix2 = matrix_from_user()

    product = matrix_mul(matrix1, matrix2)

    print('Matrix1: ', matrix1)
    print('Matrix2: ', matrix2)
    print('Result of Matrix Multiplication:', product)

This code I put under an if __name__ == "__main__": guard which allows you to import this script from another script without this part of the code being run (so you get access to the functions).


For learning reason, you can create 2d array in one row like:

matrix2 = [[vc + v*10*vr  for vc in range(0, v)] for vr in range(0, r)]

Since python is a funcational language, for learning reason, you can define a map/ reduce over matrix like:

def map(matrix, r,c, fn,summ):
 for vr in range(0, r):                  
    for vc in range(0, c): 

or with additional map-reduce over the row:

  def map(matrix, r,c, fn,fnRow,startVal,summ):
     for vr in range(0, r):
        summRow = startVal
        for vc in range(0, c): 
        fnRow(summRow, summ)

for learning reason you could implement Strassen matrix multiplication algorithm (google please), not naive one. I doubt you learn something like that.
For doing real project, use Numpy for initiations, not for high-performance operations.


I suggest following matrix_mul implementation

def matrix_mul(matrix1, matrix2):
  from operator import mul
  return [[sum(map(mul, row, col)) for col in zip(*matrix2)] for row in matrix1]
  • \$\begingroup\$ That is a nice and compact way of writing it. But I would put the import outside the function, it does cause some small overhead (even though it will only be imported once). \$\endgroup\$
    – Graipher
    Jan 25, 2018 at 9:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.