Python User Defined Functions With Code Examples

Introduction

What are functions in Python programming language?  Functions are used to perform a specific task. It is a block of codes and runs only when it is called. Functions make our program modular, clean, and easy to read, understand, read, or rewrite a block of codes. You must write a block of codes in a program in multiple places. Then you will define a function and call this function wherever required. It would be best if you do not repeat similar codes at every place.

There are two types of functions in Object Oriented Programming languages like Python.

  1. In-built Functions and
  2. User defined Functions

Inbuilt Functions 

These functions are by default available when you install Python in your device. These functions are very common in use during coding. The meaning of these functions are understood by python Interpreter. Some of the inbuilt functions are print(), type(), input(), etc. There are thousands of inbuilt functions defined in python libraries. Each for some specific task. For example, if you have to display any result then use print function.

syntax:

         print(“Hello world”)

input() function is used to take data from users . 

syntax of input function:-

name = input(“enter your name”)

age = input(“enter your age”)

Note: Syntax is rules or guidelines for writing codes in any programming language.

Use of python functions are very easy. All the codes are written in simple English language so that anyone can understand it easily.

User-defined Functions

Sometimes, inbuilt functions are not sufficient to cover your requirements during coding. Completing real time projects, a programmer defines a several functions according to client requirement. 

The functions defined and customized by programmer for matching real life requirement is called user defined function.

What is the syntax of user defined functions?

#Syntax for writing user defined function in python

def function_name(parameters):
    #statement1
    #statement2
    .
    .
    #statementn

def is a python keyword. We use def keyword to write a user defined functions.

function_name could be any taken by users.

parameter: You can put any number of parameters inside the function name.

Python statements are written inside the function body. You can add multiple lines of codes. There are not any limitation. But functions are written to bring modularity and readability of codes. Always keep in mind that your user defined functions goal should be to comlete a single task. 

Examples of User defined functions

#Write a python program to add two numbers using user defined function

def addNumbers():
    x=10
    y=20
    print(x+y)
    
addNumbers()
Output
30

Code explanation
here addNumbers is function name. This function is without parameters. Now call addNumbers(), It will print the final result

#Write a python program to add two numbers. Take numbers from the users

def add_numbers(num1,num2):
    x =num1
    y= num2
    c =x+y
    return c

num1 = int(input("Enter a Number "))
num2 = int(input("Enter a Number "))

res = add_numbers(num1,num2)
print("Sum of {} and {} is {} ".format(num1,num2,res))
Output
Enter a Number 5
Enter a Number 6
Sum of 5 and 6 is 11 

Code Explanation

 

add_numbers is parameterised function. We are passing two parameters num1 and num2.

input() function is python in-built function. It is used to take data from users. Since input() function always returns string value. To perform mathematical calculations we need numeric values. Therefore we have changed input data into int type with the help of int() function.

.format() method is used to make our result more readable and interactive

What are the four user defined functions in python?

Till now we have learned about the basics of python functions. Functions are used for performing a specific task. We define functions and tailor them according to our programming needs. Python categories user-defined functions in different-different categories. Below I have mentioned the 5 different categories of python functions. Do read the explanation of each type and implement python functions example code in your Python editor.

There are 5 types of Python user-defined Functions:

  1. Simple Functions
  2. Recursive Functions
  3. Lambda Functions
  4. Higher-Order-Functions
  5. Generator Functions

Simple Functions

Simple functions are defined by programmer to perform specific tasks and it returns values. It can be of two types parameterized and non-parameterized. We have already explained simple functions syntax and examples of simple functions in the above section.

 

Recursive Functions

Recursive functions are a type of function that calls itself. It is defined as a simple functions but this function calls itself as per requirement. Results of each calls are used as an input to reach final solutions. It is used to solve the smaller part of same problem.

What is the syntax of a Recursive Function?

#syntax of recursive function

def recursive_func(parameter):
   #base case
    if :
        return value
    else:
        #call recursive function with changed parameter
        return recursive_func(modified parameter)

Example of Recursive Function

Write a python program to print Factorial of a given number.

What is Factorial of a number? Let you want factorial of 5!(read as five factorial. ! is symbol of factorial in mathematics) . Then  5! is 5*4*3*2*1 = 120

Factorial of 0 is 1(0!=1)

#Write a python code to print factorial of a given number

def recursive_func(num):
#base case
    if num==0:
        return 1
    else:
        #recursive case
        return num*recursive_func(num-1)
    
print(recursive_func(5))
 Output

120

Code Explanation

Recursive Function can run infinitely if not handled properly. There must be a base case to handle recursive function. And recursive case must move towards the base case.

Let’s learn one more example that depicts recursive case. In this example we will learn about Fabonacci series. What is Fabonacci Series? Fabonacci series is where if 2 number is already assigned then next number is the sum of immediate two numbers in left side. For example 0,1,1,2,3,5,8,13,21 is a fabonacci series.

Write a python program to print fabonacci series 

def fibonacci_func(num):
    if num<=1:
        return num
    else:
        return (fibonacci_func(num-1)+fibonacci_func(num-2))
    
nterms = int(input("Enter Total terms to be printed "))
if nterms<=0:
    print("invalid input")
else:
    print("Fibonacci numbers are ")
    for i in range(nterms):
        print(fibonacci_func(i),end=" ")
Output

Enter Total terms to be printed 10
Fibonacci numbers are 
0 1 1 2 3 5 8 13 21 34 

Advantages Of Recursion

  1. It divides problems into smaller chunks.
  2. Very less code is required to solve bigger problems
  3. It is used for Data Structure algorithms such as tree trasversal, sorting, etc.

Disadvantages of Recursion

  1. It takes a lot of time and memory for computation
  2. Complexity increases as the size of computation increases.
  3. Need to be very careful while using recursion . If not handled properly then program can execute infinitely. this may lead to deadlock situation.

Lambda Function

In Python, Lambda function is used to create small functions where no need to write many lines of code. Lambda can take any number of arguments but it has only one expression. For defining Lambda function def keyword is not required.

Write apython function to add two numbers using Lambda.

#write a function to add two numbers.

add_numbers = lambda x,y:x+y

print(add_numbers(7,8))
output

15

in this code example, add_numbers is function name and lambda is python keyword. Lambda is short hand to fulfill function requirement in python programming.

map(), filters(), reduce() are also short hand functions available in python . We will learn more about these functions in next section of user defined functions.

High Order Function

In python, map(), filters() and reduce() are high order functions. These functions take other functions as arguments or return it  as a result. These functions enhances reusability and modularity of codes.  Let’s learn each of them one by one.

map()

map() applies a function to all the elements in a list.

syntax of map function:

map(function_name,list_name)

Write a Python program to Find sqare of each number stored in a list

numbers =[1,2,3,4,5]

squared_list = map(lambda x:x**2,numbers)
print(list(squared_list))
 Output
[1, 4, 9, 16, 25]

Result of  map() function need to be converted into list to get expected output.

You can also define function outside of map function and just pass the function name in the map function. Just look into the example.

numbers =[1,2,3,4,5]

function_lambda = lambda x:x**2

squared_list = map(function_lambda,numbers)
print(list(squared_list))
Output
[1, 4, 9, 16, 25]

filter()

filter() in python also applies on each values in list. filter returns only those values if condition is true. Lets learn by example:

Write a python program to filter even numbers in a list

numbers = [1,2,3,4,5,6]

even_numbers = filter(lambda x:x%2==0,numbers)
print(list(even_numbers))
Output
[2, 4, 6]

We can see filter function has returned only those numbers which satisfy the condition.

reduce()

In python reduce() is a part of functool module. It is applied cumulatively on the items of list. It reduces list from left to right and finally into a single value. Let’s learn by example. 

Write a python program to find the total sum of all the numbers present in a list

from functools import reduce

numbers = [1,2,3,4,5,6]
list_sum = reduce(lambda x,y:x+y,numbers)
print(list_sum)
Output
21

sorted()

In python, sorted() use function as a key for sorting.

employees = [("ray", 20), ("Krish", 29), ("Charls", 25)]
sorted_employees = sorted(employees, key=lambda x: x[1])
print(sorted_employees)
Output
[('ray', 20), ('Charls', 25), ('Krish', 29)]

Here each pair represents an employee name and age. Name at index 0 and age at index 1. In lambda function index 1 has passed . Therefore sorted results has been arranged in lower age to higher age. Lets see what will happen if index 0 is passed in lambda function.

employees = [("ray", 20), ("Krish", 29), ("Charls", 25)]
sorted_employees = sorted(employees, key=lambda x: x[0])
print(sorted_employees)
Output
[('Charls', 25), ('Krish', 29), ('ray', 20)]

In output we can see, if index 0 is passed list has sorted according to alphabetical order of name.

High Order Functions in Python are powerful. They allow to write concise and expressive code by abstracting away common patterns of data processing.

×