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

Function

Uploaded by

starlord68736
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Function

Uploaded by

starlord68736
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Function

The function is a block of organized and reusable program code that


performs a single, specific, and well-defined task.

Example 1

def display():
print("Hello")

display()

Output:

Hello

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
1
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 2

def add(x,y):
r=x+y
print("Result",r)

a=int(input("Enter 1st No:"))


b=int(input("Enter 2nd No:"))

add(a,b)

Output:

Enter 1st No: 10


Enter 2nd No: 6
Result 16

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
2
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 3

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

a=int(input("Enter 1st No:"))


b=int(input("Enter 2nd No:"))

r=add(a,b)
print("Result=",r)

Output:

Enter 1st No: 10


Enter 2nd No: 4
Result= 14

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
3
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 4.1

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

a=int(input("Enter 1st No:"))


b=int(input("Enter 2nd No:"))

addition=add
r=addition(a,b)
print("Result=",r)

Output:

Enter 1st No:11


Enter 2nd No:22
Result= 33
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
4
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 4.2

def display():
print("ABCD")
return
print("XYZ")

display()

Output:

ABCD

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
5
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 4.3

def display():
print("Hello")
return

display()
print(display())

Output:

Hello
Hello
None

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
6
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
In python programming language, a function can return more than one value.

Example 5

def add_sub(x,y):
c=x+y
d=x-y
return c,d

a=int(input("Enter 1st No:"))


b=int(input("Enter 2nd No:"))

r1,r2=add_sub(a,b)

print("Result of Addition=",r1)
print("Result of Subtraction=",r2)

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
7
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Output:

Enter 1st No:11


Enter 2nd No:4
Result of Addition= 15
Result of Subtraction= 7

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
8
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 6

def swap(x,y):
return y,x

a=int(input("Enter 1st No:"))


b=int(input("Enter 2nd No:"))

print("Before Swap:")
print("a=",a)
print("b=",b)

a,b=swap(a,b)

print("After Swap:")
print("a=",a)
print("b=",b)
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
9
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Output:

Enter 1st No:11


Enter 2nd No:22
Before Swap:
a= 11
b= 22
After Swap:
a= 22
b= 11

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
10
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 7

def update(x):
print("Inside Finction 1 :x=",x,"Address=",id(x))
x=8
print("Inside Finction 2 :x=", x, "Address=", id(x))

x=10
update(x)
print("Outside Finction :x=",x,"Address=",id(x))

Output:

Inside Finction 1 :x= 10 Address= 1351825808


Inside Finction 2 :x= 8 Address= 1351825776
Outside Finction :x= 10 Address= 1351825808

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
11
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 8

def update(lst):
print("\nIn function before update :")
print("List:", lst)
print("List Address:", id(lst))
print("Address of list elements:")
for i in range(3):
print((id(lst[i])))

lst[1]=25

print("\nIn function After update : :")


print("List:", lst)
print("List Address:", id(lst))
print("Address of list elements:")
for i in range(3):
print((id(lst[i])))

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
12
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
lst=[10, 20, 30]

print("Before function call :")


print("List:",lst)
print("List Address:",id(lst))
print("Address of list elements:")
for i in range(3):
print((id(lst[i])))

update(lst)

print("\nAfter function call :")


print("List:",lst)
print("List Address:",id(lst))
print("Address of list elements:")
for i in range(3):
print((id(lst[i])))
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
13
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Output:

Before function call :


List: [10, 20, 30]
List Address: 9848232
Address of list elements:
1348024720
1348024880
1348025040

In function before update :


List: [10, 20, 30]
List Address: 9848232
Address of list elements:
1348024720
1348024880
1348025040

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
14
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
In function After update : :
List: [10, 25, 30]
List Address: 9848232
Address of list elements:
1348024720
1348024960
1348025040

After function call :


List: [10, 25, 30]
List Address: 9848232
Address of list elements:
1348024720
1348024960
1348025040

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
15
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 9

def update(tup):
print("\nIn function before update :")
print("Tuple:", tup)
print("Tuple Address:", id(tup))
print("Address of Tuple elements:")
for i in range(3):
print((id(tup[i])))

tup[1]=25

print("\nIn function After update : :")


print("Tuple:", tup)
print("Tuple Address:", id(tup))
print("Address of Tuple elements:")
for i in range(3):
print((id(tup[i])))

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
16
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
tup=(10, 20, 30)

print("Before function call :")


print("Tuple:",tup)
print("Tuple Address:",id(tup))
print("Address of Tuple elements:")
for i in range(3):
print((id(tup[i])))

update(tup)

print("\nAfter function call :")


print("Tuple:",tup)
print("Tuple Address:",id(tup))
print("Address of Tuple elements:")
for i in range(3):
print((id(tup[i])))
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
17
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Output:

Before function call :


Tuple: (10, 20, 30)
Tuple Address: 8071728
Address of Tuple elements:
1348024720
1348024880
1348025040

In function before update :


Tuple: (10, 20, 30)
Tuple Address: 8071728
Address of Tuple elements:
1348024720
1348024880
1348025040

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
18
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Traceback (most recent call last):
File "C:/Users/Admin/PycharmProjects/function1/fun9.py", line 29, in
<module>
update(tup)
File "C:/Users/Admin/PycharmProjects/function1/fun9.py", line 9, in
update
tup[1]=25
TypeError: 'tuple' object does not support item assignment

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
19
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Local and Global variables

Global variables are those variables which are defined in the main body of the
program file.

The variable which is defined within a function is called local variable.

Example 1

a=10
print("In Global Section: a=",a,"Address=",id(a))

def show():
a=20
print("Inside function: a=", a, "Address=", id(a))

show()
print("Outside function: a=",a,"Address=",id(a))
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
20
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Output:

In Global Section: a= 10 Address= 1347631504


Inside function: a= 20 Address= 1347631664
Outside function: a= 10 Address= 1347631504

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
21
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 2

a=10
print("In Global Section: a=",a,"Address=",id(a))

def show():
global a
a=20
print("Inside function: a=", a, "Address=", id(a))

show()
print("Outside function: a=",a,"Address=",id(a))

Output:

In Global Section: a= 10 Address= 1347631504


Inside function: a= 20 Address= 1347631664
Outside function: a= 20 Address= 1347631664
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
22
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 3

a=10
print("In Global Section: a=",a,"Address=",id(a))

def show():
global b
b=20
print("Inside function: b=", b, "Address=", id(b))

show()
print("Outside function: a=",a,"Address=",id(a))
print("Outside function: b=", b, "Address=", id(b))

Output:

In Global Section: a= 10 Address= 1347631504


Inside function: b= 20 Address= 1347631664
Outside function: a= 10 Address=Dr.1347631504
Shiladitya Chowdhury
Outside function: b= 20 Address= 1347631664
Ph.D(Computer Science & Engineering)(JU)
23
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Resolution of Names

When a variable name is used in a code block, it is resolved using the


nearest enclosing scope.

If no variable of that name is found, then NameError is raised.

Example 1

def fun():
print("a=",a)

a=20
fun()

Output:

a= 20
Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
24
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
A local variable cannot be defined with the same name as global variable.
To do this we must need global statement.
Example 2

def fun():
print("a=",a)
a=10
print("a=", a)

a=20
fun()

Output:
Traceback (most recent call last):
File "C:/Users/Admin/PycharmProjects/function1/resolutionName_2.py", line 7, in
<module>
fun()
File "C:/Users/Admin/PycharmProjects/function1/resolutionName_2.py", line 2, in fun
print("a=",a) Dr. Shiladitya Chowdhury
Ph.D(Computer
UnboundLocalError: local variable 'a' referenced Science & Engineering)(JU)
before assignment 25
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 3

def fun():
global a
print("a=",a)
a=10
print("a=", a)

a=20
fun()

Output:

a= 20
a= 10

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
26
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Nested function

In case of nested functions (function inside another function), the inner function
can access variables defined in both outer as well as inner function; but the
outer function can access variables defined only in the outer function.

def outer_fun():
outer_var=10
def inner_fun():
inner_var=20
print("In Inner fun: outer variable=",outer_var)
print("In Inner fun: inner variable=",inner_var)
inner_fun()
print("In Outer fun: outer variable=", outer_var)
print("inner variable=",inner_var)

outer_fun()

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
27
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Output:

Traceback (most recent call last):


File "C:/Users/Admin/PycharmProjects/function1/nestedfun1.py", line 11,
in <module>
outer_fun()
File "C:/Users/Admin/PycharmProjects/function1/nestedfun1.py", line 9, in
outer_fun
print("inner variable=",inner_var)
NameError: name 'inner_var' is not defined
In Inner fun: outer variable= 10
In Inner fun: inner variable= 20
In Outer fun: outer variable= 10

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
28
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
If a variable in the inner function is defined with the same name as that of a
variable defined in the outer function, then a new variable is created in the
inner function.

def outer_fun():
var=10
def inner_fun():
var=20
print("In Inner fun: var=",var,"Address=",id(var))
inner_fun()
print("In Outer fun: var=", var,"Address=",id(var))

outer_fun()

Output:

In Inner fun: var= 20 Address= 1347631664


In Outer fun: var= 10 Address= 1347631504

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
29
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Keyword Arguments

Python allows functions to be called using keyword arguments in which the


order (or position) of the arguments can be changed.

Example 1

def display(name,roll,avgmarks):
print("Name:",name)
print("Roll:",roll)
print("Avg Marks:",avgmarks)

display(roll=10,avgmarks=78.25,name="Raja Roy")

Output:

Name: Raja Roy


Roll: 10
Avg Marks: 78.25 Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
30
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 2

def display(ename,age,salary):
print("Name:",ename)
print("Age:",age)
print("Salary:",salary)

n="Arun Das"
a=35
sal=50000
display(salary=sal,ename=n,age=a)

Output:

Name: Arun Das


Age: 35
Salary: 50000

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
31
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Default Arguments
Python allows users to specify function arguments that can have default
values. So, the function can be called with fewer arguments than it is defined to
have.
Example 1
def display(name,course="B.Tech"):
print("Name:",name)
print("Course:",course)

display("Raja Roy")
display("Amit Das","BCA")
display("Arup Saha","MCA")
Output:
Name: Raja Roy
Course: B.Tech
Name: Amit Das
Course: BCA
Name: Arup Saha Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
Course: MCA Assistant Professor, Dept. of MCA
32
Techno Main Saltlake, Kolkata 700091
We can specify any number of defaults arguments to a function.
Example 2
def display(name,course="B.Tech",age=18):
print("Name:",name)
print("Course:",course)
print("Age:",age)
display("Raja Roy")
display("Amit Das","BCA")
display("Arup Saha","MCA",21)
Output:
Name: Raja Roy
Course: B.Tech
Age: 18
Name: Amit Das
Course: BCA
Age: 18
Name: Arup Saha
Course: MCA Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
Age: 21 33
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
If we have default arguments, then they must be written after the non-default
arguments.

Example 3

def display(name,course="B.Tech",age):
print("Name:",name)
print("Course:",course)
print("Age:",age)

display("Amit Das","BCA",18)
display("Arup Saha","MCA",21)

Output:

C:\Users\Admin\PycharmProjects\function1\venv\Scripts\python.exe
C:/Users/Admin/PycharmProjects/function1/defaultArg3.py
File "C:/Users/Admin/PycharmProjects/function1/defaultArg3.py", line 1
def display(name,course="B.Tech",age):
^ Dr. Shiladitya Chowdhury
SyntaxError: non-default argument follows
Ph.D(Computer default
Science argument
& Engineering)(JU)
34
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Variable-length Arguments

In some situations, it is not known in advance how many arguments


will be passed to a function.

In such case, Python allows programmers to make function calls with


arbitrary (or any) number of arguments.

The arbitrary number of arguments passed to a function basically


forms a tuple before being passed into function.

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
35
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 1

def display(name,*fevsubs):
print("Name:",name,"likes following subjects:")
for i in fevsubs:
print(i)

display("Raja Roy","Mathematics")
display("Amit Das","Mathematics","Biology")
display("Arup Saha","Mathematics","Physics","Chemistry")
display("Arun Dutta","Biology","Mathematics","Physics","Chemistry")

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
36
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Output:

Name: Raja Roy Likes following subjects:


Mathematics
Name: Amit Das Likes following subjects:
Mathematics
Biology
Name: Arup Saha Likes following subjects:
Mathematics
Physics
Chemistry
Name: Arun Dutta Likes following subjects:
Biology
Mathematics
Physics
Chemistry

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
37
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 2

def show(a,*b):
print("a=",a)
print("b:",b)
for i in b:
print(i)

show(5,10,20,30)
show("Arun Dutta","Biology","Mathematics","Physics","Chemistry")

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
38
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Output:

a= 5
b: (10, 20, 30)
10
20
30
a= Arun Dutta
b: ('Biology', 'Mathematics', 'Physics', 'Chemistry')
Biology
Mathematics
Physics
Chemistry

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
39
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Recursion
A function that calls itself is known as a recursive function; and this
technique is known as recursion.

Recursion one can solve problems in easy way while its iterative solution
is very big and complex.

Recursion uses more processor time.

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
40
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Example 1

def fact(n):
f=1
if n==0 or n==1:
return 1
else:
return n*fact(n-1)

n=int(input("Enter No:"))
if n>=0:
r=fact(n)
print("Result=",r)
else:
print("Wrong Input")

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
41
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Output:

Enter No:6
Result= 720

Enter No:-4
Wrong Input

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
42
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Function redefinition
We can redefine function in Python programming language.

Example 1

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

a=int(input("Enter 1st No:"))


b=int(input("Enter 2nd No:"))

r=add(a,b)
print("Result=",r)

def add(x,y,z):
s=x+y+z
return s Dr. Shiladitya Chowdhury
Ph.D(Computer Science & Engineering)(JU)
43
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
a=int(input("Enter 1st No:"))
b=int(input("Enter 2nd No:"))
c=int(input("Enter 3rd No:"))

r=add(a,b,c)
print("Result=",r)

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
44
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091
Output:

Enter 1st No:1


Enter 2nd No:2
Result= 3
Enter 1st No:10
Enter 2nd No:20
Enter 3rd No:30
Result= 60

Dr. Shiladitya Chowdhury


Ph.D(Computer Science & Engineering)(JU)
45
Assistant Professor, Dept. of MCA
Techno Main Saltlake, Kolkata 700091

You might also like