Python Functions With Parameters and Return

Advertisements
Advertisements

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.

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.

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

Bestseller

Python Programming: Using Problem Solving Approach

Python Programming is designed as a textbook to fulfil the requirements of the first-level course in Python programming. It is suited for undergraduate degree students of computer science engineering, information technology as well as computer applications. This book will enable students to apply the Python programming concepts in solving real-world problems. The book begins with an introduction to computers, problem solving approaches, programming languages, object oriented programming and Python programming. Separate chapters dealing with the important constructs of Python language such as control statements, functions, strings, files, data structures, classes and objects, inheritance, operator overloading and exceptions are provided in the book. Each chapter ends with objective-type questions, review questions, programming and debugging exercises to facilitate revision and practice of concepts learnt.


Advertisements
Advertisements
Advertisements