0% found this document useful (0 votes)
6 views

FUNCTIONS IN PYTHON

The document provides an overview of functions in Python, including their advantages, types (built-in, module, and user-defined), and components such as headers, signatures, and return statements. It also discusses invoking functions, parameter types, variable scopes, and the differences between local and global variables. Additionally, it includes examples of various function types and their applications in Python programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

FUNCTIONS IN PYTHON

The document provides an overview of functions in Python, including their advantages, types (built-in, module, and user-defined), and components such as headers, signatures, and return statements. It also discusses invoking functions, parameter types, variable scopes, and the differences between local and global variables. Additionally, it includes examples of various function types and their applications in Python programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

© Copyright Reserved by Debanjan Gupta

FUNCTIONS
A function/method is a program module which is used at different instances in a program to
perform a specific task.
Advantages of a function

• it reuses the segment of operations, as and when necessary, by simply using the
method name.
• it divides a complex computational task into a collection of smaller methods so that
the problem becomes easier, object specific and modular.
• A program that uses method occupies less memory space and executes faster.

TYPES OF FUNCTIONS IN PYTHON


1. Built-in Functions:
They are defined by the language creator and provided within the framework of the
language. They are independent, which means they are not included in any module.
Some built-in functions are:
input(), print(), eval()

2. Functions in a Module:
Module in Python is a file with .py extension. It defines the functions, classes and
variables. To use a function of a specific module, the name of the module is used along
with import keyword.
Ex:
import math
vi=math.sqrt(9)
print(v1)

3. User Defined Function:


They are also known as UDF, they are created and defined by the users of the
language. They are not exclusively created by the language developers.
Defining an UDF
Syntax
def <Function name> (Parameter list) :
// ……. Statements …………
…………………………………….//
return value
© Copyright Reserved by Debanjan Gupta

Example
def sum(a,b):
c=a+b
return c

COMPONENTS OF A METHOD
Header - It is the first line of a function which contains function name and a list of parameters,
followed by indentation (:). A method header is also referred to as method prototype or
function prototype.

def sum(a,b):

Function Signature – Signature is basically identification of a person, Similarly a function


signature is the identification of a function. It signifies a function that is to be invoked for a
specific operation. A method signature is written by using function name along with
parameters.
Ex: sum (a,b):
Function name – The function name should preferably be related to the task the specific
method performs.
Parameter List – It is a list of variables with their respective datatypes. The receives values
passed during method call for internal computation.
Method block – The function body contains a set of statements which are to be executed.
These statements written under method header under indentation(:).
Return Statement – A statement that sends back the result/ outcome value from the
method to its caller program.
FEATURES OF return STATEMENT
1. It is always used at the end of a method.
2. No statement in the method will be executed after the return statement
3. Return statement can return multiple values from a method.
4. A non-returnable function may or may not use return statement.
5. Once control exits from the method, it can’t reappear into the method block for any
further execution unless the method is called again.
© Copyright Reserved by Debanjan Gupta

INVOKING A FUNCTION
A process of using a function in a program is referred to as calling a method or invoking a
method.
// A program to find sum of two numbers by using a method.

def sum(a,b):
c=a+b
return (c)
#Main program
num1=eval(input("Enter a number "))
num2=eval(input("Enter another number "))
print(sum(num1,num2))

ACTUAL AND FORMAL PARAMETERS:


The parameters which are defined in the function header are known as Actual parameters,
whereas, the parameters passed in the function call statement are known as Formal
Parameters.

RETURNABLE AND NON-RETURNABLE FUNCTIONS


A function which returns a value to its caller program is a returnable function, whereas a
function that does not return any value to its caller program is known as a non-returnable
function.

EXAMPLES:
// Python code to print factorial of a number using an UDF fact()
# Using a returnable function:
def fact(n):
f=1
for i in range(1,n+1):
f*=i
return f
#Main program
num=eval(input("Enter a number "))
print(f'Factorial of {num} is',fact(num))

# Using non-returnable function:


def fact(n):
f=1
for i in range(1,n+1):
f*=i
© Copyright Reserved by Debanjan Gupta

print(f'Factorial of {num} is',f)


return
#Main program
num=eval(input("Enter a number "))
fact(num)

PARAMETERIZED AND NON-PARAMETERIZED FUNCTIONS


Parametrized:
A function that is defined with a set of parameters along with function name in the header
is known as parameterized function. In this case, the values are passed at the time of calling
the method

Non-Parameterized:
A function that does include parameters along with function name in the header is known
as non-parameterized function.
Ex: #Use of non-parameterized method.
def fact():
n=5;
f=1
for i in range(1,n+1):
f*=i
print(f'Factorial of {n} is',f)
return
#Main program
fact()

TYPES OF ARGUMENTS:
(a) Positional Arguments
Positional arguments the provide in corresponding order of the parameters. If three
arguments are to be passed to the function, the first argument goes to the first
parameter, second argument to the second parameter and third argument to the
third parameter.

Ex:
def volume(len,brd,hgt):
vol=len*brd*hgt
return vol
# Main Program
l=eval(input("Enter the length "))
b=eval(input("Enter the breadth "))
h=eval(input("Enter the height "))
print("The volume is",volume(l,b,h)
© Copyright Reserved by Debanjan Gupta

In the above example, the function is called with arguments volume(l,b,h) ,


which will be passed to parameters in the header, in the order of
volume(len,brd,hgt)

(b) Default Arguments


When arguments are assigned to the parameters directly using (=) sign. In such case,
the corresponding arguments are not passed.
Ex:
def volume(len=12.6,brd=10.5,hgt=9.6):
vol=len*brd*hgt
return vol
# Main Program
print("The volume is",volume())

(c) Keyword Arguments


These arguments give the flexibility to specify the arguments in any order. It means,
during function call, one will have the flexibility to write an argument in any order,
provided that the argument order and parameter names should be same.
Ex:
def volume(len,brd,hgt):
vol=len*brd*hgt
return vol
# Main Program
print("The volume is",volume(len=12.5,brd=10.5,hgt=9.5))

SCOPE OF VARIABLES:
(a) Local Scope:
Local scope is the limited range of program area (i.e. a block or function). A variable
declared within a local scope is said to be local variable and its use is restricted
outside the scope.
Ex:
#Python code to illustrate usage of a local variable
def test():
d=26-15;
print("Difference = ",d)
#Main Program
p=d**2
print("Result= ",p)
© Copyright Reserved by Debanjan Gupta

This code will produce an error as variable d is being accessed outside the scope of
the function block in which it is declared.

The code therefore produces an NameError

(b) Global scope


The variables declared within the main body or outside the function block are
called global variables and thus belong to global scope.
It means the variable available outside the function are global and be used
throughout the program.
Ex:
#Python code to illustrate usage of a global variable
def volume():
v=22/7*r*r*h
ar=2*22/7*r*h
print("Radius ",r)
print("Height ",h)
print("Volume ",v)
print("Area ",ar)
#Main Program
r=14
h=10
volume()

With reference to the code given above, the variable s ‘r’ and ‘h’ are defined within the
main program body and hence are global variables and their scope usage is also within the
function block.
The code works without any error.

SPECIAL CASES:
There are some special cases with reference to scope of variables:
(a) Using variables with same name in local and global scope:
© Copyright Reserved by Debanjan Gupta

The local and global variables declared with same name are treated differently by
the Python interpreter. The variables declared within the function block are treated
as local variables, whereas the variables declared outside the function block are
global variables.
Ex:
def sample():
num=20
print("Value of num as local variable= ",num)
#Main Program
num=25
print("Value of num as global variable= ",num)
sample()

output:

The above example shown above contains variables with same name (num) in the main
program as well as in the function body. Hence both of them are showing their respective
values as global and local variables.

(b) Using a global variable in local scope


A global variable can be accessed within the local scope but in no way can the value
of a global variable can be updated in local scope. If its done it will produce and
error.

Ex:
#Updating global variables in local scope
def sample():
num=num+5
print("Value of num as local variable= ",num)
#Main Program
num=25
print("Value of num as global variable= ",num)
sample()

output
© Copyright Reserved by Debanjan Gupta

To overcome this problem, refer the global variable in local scope with the help of keyword
global. The global keyword will allow you to update the global variable in local scope.
Ex:
#Updating global variables in local scope with the help of glo
bal
keyword
def sample():
global num
num=num+5
print("Value of num as local variable= ",num)
#Main Program
num=25
print("Value of num as global variable= ",num)
sample()

Output:

DIFFERENCE BETWEEN LOCAL AND GLOBAL VARIABLES:

Local Variables Global Variables

Local variables are declared within a Global variable is declared outside


function or method block function block and also inside function
block using ‘global’ keyword.

It is accessible within the function block It is accessible throughout the program.


only.

PASSING MUTABLE AND IMMUTABLE ARGUMENTS TO FUNCTION PARAMETERS:


(a) Passing immutable Type values to function (Pass by value)
The datatypes such as int, float, string etc are immutable. When an immutable
datatype is passed to a function, the actual parameters are copied to the formal
parameters in such a way that any change made in the formal parameter does not
affect the actual parameter.
© Copyright Reserved by Debanjan Gupta

Ex:
def display(x,y):
x=x*2
y=y*2
print("Formal paramters after operation:")
print("First value ",x)
print("Second value ",y)
#Main
a=5
b=6
print("Actual parameters before passing to funtion:")
print("First value ", a)
print("Second value ", b)
display(a,b)
print("Actual parameters after function operation:")
print("First value ", a)
print("Second value ", b)

Output:

(b) Passing mutable type values to function (Pass by reference):


In this process, the actual parameters are passed to the formal parameters in such a way
that any change made in the formal parameter will also result in a change in the actual
parameter.
Ex:
def change(MyList):
print("List Received ",MyList)
p=len(MyList)
for i in range(p):
MyList[i]+=5
print("List elements ",MyList)
# Main

MList=[10,20,30,40,50]
print("List before passing to the function ",MList)
© Copyright Reserved by Debanjan Gupta

change(MList)
print("List after to the function ",MList)
output:

SAMPLE CODES:
Write a Python code to accept an integer number and pass it to a function which returns
its factors. Finally display whether the number is prime or not.
def factors(num):
count=0
for i in range(1,num+1):
if num%i==0:
count+=1
return count

#Main Program
number=int(input("Enter a number "))
if factors(number)==2:
print(f'{number} is Prime')
else:
print(f'{number} is not Prime')

Write a Python code to accept a word and pass it to a function. The function checks
whether the word is palindrome or not. It returns 1 if the word is palindrome, otherwise
returns 0.
def checkPalin(word):
reverse=word
if reverse[::-1]==reverse:
return 1
else:
return 0
#Main Program
wrd=(input("Enter a word "))
wrd=wrd.upper()
if checkPalin(wrd)==1:
print("Its Palindrome")

else:
print("Not Palindrome")
© Copyright Reserved by Debanjan Gupta

Write a Python code to assign some names in a list. Pass the list to a function and arrange
the names in alphabetical order by using ‘Bubble Sort’ Technique. Display the arranged
names.
def Arrange(MyList):
size=len(MyList)
for i in range (0,size):
for j in range(0,size):
if MyList[i]<MyList[j]:
temp=MyList[i]
MyList[i]=MyList[j]
MyList[j]=temp
return MyList
#Main Program
NList=["Rohit","Ajay","Deepak","Shekhar","Vikash","Karen"]
print("Elements in the List")
print(NList)
print("List after arrangement:")
print(Arrange(NList))

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

You might also like