Python Documents
  • Data Types In Python
  • Variables In Python
  • Operators In Python
  • User Input In Python
  • Type Casting In Python
  • Strings In Python
    • String CheatSheet
  • Conditional Statements In Python
  • Lists In Python
    • List CheatSheet
  • Sets
  • Tuples in Python
  • Dictionary in Python
  • Functions In Python
  • File Handling In Python
  • Branching using Conditional Statements and Loops in Python
  • Numerical Computing with Python and Numpy
  • String CheatSheet
Powered by GitBook
On this page
  • What are Functions ?¶
  • Advantage of Functions in Python :¶
  • Types of a Function :¶
  • Two Important Aspects of a Function :¶
  • Creating / Defining a Function :¶
  • Function to print Hello World : ¶
  • Calling a Function :¶
  • Parameters and Arguments in a Function :¶
  • Function to add two numbers :¶
  • Default Parameters in a Function :¶
  • Exercise :¶
  • Keyword Arguments in Python :¶
  • Arbitrary Arguments :¶
  • Calling a function as an argument :¶
  • Types of Functions :¶
  • return multiple values to function :¶
  • Recursion :¶
  • Lambda Function :¶
  • How to use lambda Functions in Python?¶
  • Example of Lambda Function in python:¶
  • Assignment :¶

Functions In Python

PreviousDictionary in PythonNextFile Handling In Python

Last updated 2 years ago

What are Functions ?¶

Function is one of the most important aspect of Python Program. Function is a set of code that does a particular task.

The Function helps to programmer to break the program into the smaller part. It organizes the code very effectively and avoids the repetition of the code. As the program grows, function makes the program more organized.

Imagine a Program where we need to do addition more than 100 times. To do addition 100 time we will have to write same code for 100 times.

Function can be of a huge help here. Once we make a function of addition , we will call it everytime we need to add.

Advantage of Functions in Python :¶

There are the following advantages of Python functions.

1.We can avoid rewriting the same logic/code again and again in a program.Reusability of code makes program better.

2.We can call Python functions multiple times in a program and anywhere in a program.

3.We can track a large Python program easily when it is divided into multiple functions.

Types of a Function :¶

There are two types of Functions , Explained below :

1.Built - in Functions:

Built -in functions are the functions that are predefined in Python. For Example : print() , type()

2.User Defined Functions :

User Defined Functions are the functions that a user defines for a Particular task.

Two Important Aspects of a Function :¶

1.Defining a Function :

Defining a function means we need to define what specific task will our function do.

2.Calling a Function :

Calling a function means whenever we need to do the task, we need to call the function.

We cannot call a function before defining it.

Creating / Defining a Function :¶

Python provides the def keyword to define the function. The syntax of the define function is given below.

In [ ]:

def function_name():
    statement1
    statement2

Function to print Hello World : ¶

In [1]:

def myfunc():
    print("hello world")

Now if we try to run above program , nothing happens. Because we have define the function but we haven't called it yet.

Calling a Function :¶

We can call function simply with the help of this syntax :

So we will get desired result by merging these two codes together.

In [2]:

#Defining a Function
def myfunc():
    print("hello world")

#Calling a Function
myfunc()

Parameters and Arguments in a Function :¶

Parameters are types of information which can be passed into the function. The Parameters are specified in the parentheses. We can pass any number of arguments, but they must be separated with a comma.

Arguments are the values passed while calling a Function.

In [ ]:

def function_name(parameters):
    statement1
    statement2

Function to add two numbers :¶

In [3]:

#defining a Function
def add(x,y):    #x and y are Parameters
    print(x+y)

add(5,6)  #5 and 6 are Arguments.
    

While calling a function 5 is assigned to x and 6 is assigned to y.

Default Parameters in a Function :¶

Default Parameters work when there are no arguments passed while calling a function. For Example :

In [4]:

#Defining a Function
def add(x=0,y=0):     #0 is the default value for x and y 
    print(x+y)

add()   #calling a Function with no arguments

Default Parameters work only when there is no arguments passed. In Below Code arguments passed while calling be passed.

In [5]:

#Defining a Function
def add(x=0,y=0):     #0 is the default value for x and y 
    print(x+y)

add(7,9)   #calling a Function with no arguments

Exercise :¶

What will be the output of the following program?

In [ ]:

def mul(x=5,y=3,z=7):
    print(x*y*z)

    
mul(7,9)

Keyword Arguments in Python :¶

You can also send arguments with key=value pair in function. This way you need not to worry about order of passing arguments. For Example:

In [3]:

def sub(x,y):
    print(x-y)


sub(y=3,x=5)

Arbitrary Arguments :¶

If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition. It creates a tuple of arguments and pass it into function. By using arbitrary arguments, we can pass any number of Arguments. For Example :

In [4]:

def add(*x):   #*x is an arbitrary argument.
    print(x)

add(5,3,3,7,8,9)  

From above code , it is clear that arbitrary argument creates a tuple of parameters and pass it. How can we use it to add all the values? let's continue this code to achieve desired result.

In [5]:

def add(*x):   #*x is an arbitrary argument.
    s = 0
    for i in x : 
        s = s+i
    
    print(f'sum of numbers is {s}')
    

add(5,3,3,7,8,9)  

You can pass almost anything in function as an argument like number,string,list,set,dictionary or even a function.

Calling a function as an argument :¶

In [1]:

def hello(x):
    x('hello world')

hello(print)

Types of Functions :¶

There are two types of functions which are as follows:

Non - Return Type Function : Non return type functions are the functions that do not return any values. A function that does not return any values returns None. For Example :

In [2]:

def add(x,y):
    print(x+y)

value = add(5,3)
print(f'returned value to calling function is : ', value)
8
returned value to calling function is :  None

Here You can see add function did not return any value. It is known as no return type function. We have worked yet only on non return type Function.

Return Type Function : Return type function are the functions that return value. We use keyword return to return values to calling Function. For Example :

In [3]:

def add(x,y):
    return x+y

value = add(5,3)
print(f'returned value to calling function is : ', value)
returned value to calling function is :  8

return multiple values to function :¶

You can also return multiple values to function by using comma separator. It will internally create all values into a tuple and will return a tuple. For Example :

In [4]:

def calc(x,y):
    return x+y , x*y , x/y , x**y

value = calc(2,2)
print(value)

As you can see, it returned a tuple of addition , multiplication , division and exponent. But what if we want all values separated . We can use concept of Assigning multiple values in multiple variable. For Example :

In [5]:

def calc(x,y):
    return x+y , x*y , x/y , x**y

add,mul,div,exp = calc(2,2)
print(f'addition : {add}, multiplication : {mul} , division : {div} , exponent : {exp}')
addition : 4, multiplication : 4 , division : 1.0 , exponent : 4

Recursion :¶

The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function.

In more simpler terms , when a function calls itself is known as recursion. For Example :

Factorial of a number with the help of recursion :

In [6]:

def facto(x):
    if(x==1):      #x = 5 , hence it will go to else
        return 1
    else:
        return x * facto(x-1)      #value that returns is 5*facto(4)

fact = facto(5)  #calling a function
print('factorial is : ',fact)

facto(5) will return 5 $*$ facto(4) which means fact = 5 $*$ facto(4)

facto(4) will return 4 $*$ facto(3) which means fact = 5 $*$ 4 $*$ facto(3)

facto(3) will return 3 $*$ facto(2) which means fact = 5 $*$ 4 $*$ 3 $*$ facto(2)

facto(2) will return 2 $*$ facto(1) which means fact = 5 $*$ 4 $*$ 3 $*$ 2 $*$ facto(1)

facto(1) will return 1 which means fact = 5 $*$ 4 $*$ 3 $*$ 2 $*$ 1

Lambda Function :¶

In Python, an anonymous function is a function that is defined without a name.

While normal functions are defined using the def keyword in Python, anonymous functions are defined using the lambda keyword.

Hence, anonymous functions are also called lambda functions.

How to use lambda Functions in Python?¶

A lambda function in python has the following syntax.

Lambda functions can have any number of arguments but only one expression. The expression is evaluated and returned. Lambda functions can be used wherever function objects are required.

In [ ]:

lambda arguments: expression

Example of Lambda Function in python:¶

Here is an example of lambda function that squares the input value :

In [7]:

sq = lambda b : b**2

value  = sq(2)
print(value)

In the above program, lambda b: b ** 2 is the lambda function. Here b is the argument and b ** 2 is the expression that gets evaluated and returned. This function has no name. This function is very same like this :

In [8]:

def sq(b):
    return b**2

value = sq(2)
print(value)

Lambda function is used whenever we want to do small tasks, small functions

Assignment :¶

1.Write a function to calculate area and perimeter of a rectangle.

2.Write a function to calculate area and circumference of a circle

3.Print multiplication table of user input number by using recursion.

4.Write a function “perfect()” that determines if parameter number is a perfect number. Use this function in a program that determines and prints all the perfect numbers between 1 and 1000. [An integer number is said to be “perfect number” if its factors, including 1(but not the number itself), sum to the number. E.g., 6 is a perfect number because 6=1+2+3].

5.Write a function to check if a number is prime or not.