Python Functions With Parameters and Return

Python programming allows function to take some parameters and compute them and return a value. This is very efficient method of programming when it clearly defined what inputs a function will take and what output it returns.

Advertisements

Python Program That Compute Sum Of Two Matrix

In this example, we will create two matrix using lists and use python functions to pass the matrix and add them and return a sum_matrix.

# Program to add two matrix and return the final matrix
# print the output 
matrixOne = [[2,3],[1,1]]
matrixTwo = [[4,5],[7,2]]
sum_matrix = [[0,0],[0,0]]
def add_m():
    m3 = [[0,0],[0,0]]
    for i in range(2):
       for j in range(2):
          m3[i][j] = matrixOne[i][j] + matrixTwo[i][j]
    return m3
sum_matrix = add_m()
for i in range(0,2):
    for j in range(0,2):
          print(sum_matrix[i][j], end=" ")
    print()

In the program above, the function receives two matrix of size 2 x 2 and adds them to m3. The matrix m3 is returned as the final matrix.

Advertisements

The function is called with matrices as arguments and the output is assigned to sum_matrix. It means the function will return m3 matrix and assign it to sum_matrix. Then we use a nested loop to display the content of sum_matrix. Output of the above program is given below.

====== RESTART: C:\Python_projects\Functions\Add_Matices.py =========
6 8 
8 3 
>>> 

In the next article, we will discuss a new topic.

Advertisements

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.