FUNCTIONS IN PYTHON
FUNCTIONS IN PYTHON
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.
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)
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):
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))
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))
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
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.
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.
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:
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:
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