0% found this document useful (0 votes)
47 views18 pages

Functions

1. A function is a block of code that performs a specific task. Functions can take in parameters and return values. 2. Using functions makes programs easier to develop, test, reuse code, and improve readability. Code can be divided among team members and functions allow code to be reused in different programs. 3. Variables used inside functions have local scope, while global variables declared outside functions can be accessed within functions using the global keyword.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views18 pages

Functions

1. A function is a block of code that performs a specific task. Functions can take in parameters and return values. 2. Using functions makes programs easier to develop, test, reuse code, and improve readability. Code can be divided among team members and functions allow code to be reused in different programs. 3. Variables used inside functions have local scope, while global variables declared outside functions can be accessed within functions using the global keyword.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 18

FUNCTION

INTRODUCTION
A function is a programming block of codes which
is used to perform a single, related task. It only runs
when it is called. We can pass data, known as
parameters, into a function. A function can return
data as a result.

We have already used some python built in


functions like print(),etc.But we can also create
our own functions. These functions are called
user- defined functions.
ADVANTAGES OF USING
FUNCTIONS:
1. Program development made easy and fast : Work can be divided among project
members thus implementation can be completed fast.
2.Program testing becomes easy : Easy to locate and isolate a faulty function for
further investigation
3.Code sharing becomes possible : A function may be used later by many other
programs this means that a python programmer can use function written by
others, instead of starting over from scratch.
4.Code re-usability increases : A function can be used to keep away from rewriting
the same block of codes which we are going use two or more locations in a
program. This is especially useful if the code involved is long or complicated.
5.Increases program readability : The length of the source program can be
reduced by using/calling functions at appropriate places so program become
more readable.
6.Function facilitates procedural abstraction : Once a function is written,
programmer would have to know to invoke a function only ,not its coding.
7.Functions facilitate the factoring of code : A function can be called in other
function and so on…
CREATING & CALLING A FUNCTION (USER
DEFINED)/FLOW OF EXECUTION
A function is defined using the def keyword in
python.E.g. program is given below.

def my_own_function(): #Function block/


definition/creation
print("Hello from a
function")
#program start here.program code
print("hello before calling a function")
my_own_function() #function calling.now function codes will be executed
print("hello after calling a function")
Save the above source code in python file and execute
it
VARIABLE’S SCOPE IN
FUNCTION
There are three types of variables with the view of scope.
1. Local variable – accessible only inside the functional block where it is declared.
2. Global variable – variable which is accessible among whole program using
global keyword.
3. Non local variable – accessible in nesting of functions,using nonlocal keyword.
Local variable program: Global variable program:
def fun(): def fun():
s = "I love India!" #local variable global s #accessing/making global variable for fun()
print(s) print(s)
s = "I love India!“ #changing global variable’s value
s = "I love World!" print(s)
fun() s = "I love world!"
print(s) fun()
Output: print(s)
I love India! Output:
I love World! I love world!
I love
India! I
love India!
VARIABLE’S SCOPE IN
FUNCTION
#Find the output of below program
def fun(x, y): # argument /parameter x and
y global a
a = 10
x,y = y,x
b = 20
b = 30
c = 30
print(a,
b,x,y)
a, b, x, y =
1, 2, 3,4
fun(50, 100) #passing value 50 and 100 in parameter x and y
of function fun()
VARIABLE’S SCOPE IN
FUNCTION
#Find the output of below program
def fun(x, y): # argument /parameter x and
y global a
a = 10
x,y = y,x
b = 20
b = 30
c = 30
print(a,b,x,y)

a, b, x, y = 1, 2, 3,4
fun(50, 100) #passing value 50 and 100 in
parameter x and y of function fun()
print(a, b, x, y)
OUTPUT :-
10 30 100
50
VARIABLE’S SCOPE IN FUNCTION

Global variables in nested


function
def fun1():
x = 100
def fun2():
global
x x =
200
print("Befor OUTPUT:
e calling Before calling fun2:
fun2: " + 100 Calling fun2 now:
fun1()
str(x)) After calling fun2: 100
print("x in main: " +
print("Callin x in main: 200
str(x))
g fun2
now:")
fun2()
print("After
VARIABLE’S SCOPE IN
FUNCTION
Non local variable
def fun1():
x = 100
def
fun2():
nonloc
al x
#cha
nge
print("After
it to calling fun2: " + OUTPUT:
str(x))
globa Before calling fun2:
x=50l or 100 Calling fun2 now:
fun1()remo
print("x
ve in main: " +
After calling fun2: 200
str(x))
this x in main: 50
decla
ratio
FUNCTION PARAMERTER
Parameters / Arguments Passing and return value
These are specified after the function name, inside the parentheses.
Multiple parameters are separated by comma.The following example has a
function with two parameters x and y. When the function is called, we pass
two values, which is used inside the function to sum up the values and
store in z and then return the result(z):
def sum(x,y): #x, y are formal arguments
z=x+y
return z #return the value/result
x,y=4,5
r=sum(x,y) #x, y are actual arguments
print(r)
Note :- 1. Function Prototype is declaration of function with name
,argument and return type. 2. A formal parameter, i.e. a parameter, is in
the function definition. An actual parameter, i.e. an argument, is in a
function call.
FUNCTION ARGUMENTS
Function Arguments
Functions can be called using following types of formal arguments −
• Required arguments/ Positional parameter - arguments passed in correct positional order
• Keyword arguments - the caller identifies the arguments by the parameter name
• Default arguments - that assumes a default value if a value is not provided to argu.
• Variable-length arguments – pass multiple values with single argument name.

#Required arguments #Keyword arguments


def fun( name,
def square(x): age ):
z=x*x "This prints a passed info into
return z this function"
print ("Name: ", name)
r=square() print ("Age ",
print(r) age) return;
#In above function square() we have to
definitely need to pass some value to # Now you can
argument x. call printinfo
function
fun( age=15,
name="mohak" )
# value 15 and mohak is being passed
to relevant argument based on
FUNCTION
#Default #Variable length arguments
def sum( *vartuple ):
arguments / s=0
#Default Parameter for var in
def sum(x=3,y=4): vartuple:
z=x+y s=s+int(var)
return z return s;

r=sum() r=sum( 70, 60, 50 )


print(r) print(r)
r=sum(x=4) r=sum(4,5)
print(r) print(r)
r=sum(y=45)
print(r) #now the above function sum()
can sum n number of values
#default value of x and y is
being used when it is not
LAMDA
Python Lambda
A lambda function is a small anonymous function which
can take any number of arguments, but can only have one
expression.

E.g.

x = lambda a, b : a * b
print(x(5, 6))

OUTPUT:
30
Mutable/immutable
properties
of data objects w/r
function

Everything in Python is an object,and every objects in Python


can be either mutable or immutable.
Since everything in Python is an Object, every variable
holds an object instance. When an object is initiated, it is
assigned a unique object id. Its type is defined at
runtime and once set can never change, however its
state can be changed if it is mutable.
Means a mutable object can be changed after it is
created, and an immutable object can’t.

Immutable objects:
Mutable objects: int, set,
list, dict, float,
bytecomplex,
array string, tuple,
frozen
set ,bytes
MUTABLE/IMMUTABLE PROPERTIES OF DATA OBJECTS
W/R FUNCTION
How objects are passed to
#Pass by reference Functions #Pass by value
def updateList(list1): def updateNumber(n):
print(id(list1)) print(id(n))
list1 += [10] n += 10
print(id(list1)) print(id(n))
n = [50, 60] b =5
print(id(n)) print(id(b))
updateList(n) updateNumber
print(n) (b) print(b)
print(id(n)) print(id(b))
OUTPUT OUTPUT
34122928 1691040064
34122928 1691040064
34122928 1691040224
[50, 60, 10] 5
34122928 1691040064
#In above function list1 an object is being passed #In above function value of variable b is
and its contents are changing because it is not being changed because it is immutable
mutable that’s why it is behaving like pass by that’s why it is behaving like pass by value
reference
PASS LIST TO FUNCTION

Passing a list as an argument actually passes a reference to the list, not a copy of the list.
Since lists are mutable, changes made to the elements referenced by the parameter change
the same list that the argument is referencing.

e.g. OUTPUT:
def 1
dosomething( thelist ): 2
3
for element in thelist: red
print (element) green
dosomething( ['1','2','3'] ) Blue
Note:- List is mutable datatype that’s why it
alist = ['red','green','blue'] treat as pass by reference.It is already explained
dosomething( alist ) in topic Mutable/immutable properties of data
objects w/r function
PASS STRING TO A FUNCTION

String can be passed in a function as argument but it is used


as pass by value.It can be depicted from below program. As it
will not change value of actual argument.
e.g.
def welcome(title):
title="hello"+title

r="Mohan"
OUTPUT
welcome(r) Mohan
print(r)
PASS TUPLE TO A FUNCTION
in function call, we have to explicitly define/pass the tuple.It
is not required to specify the data type as tuple in formal
argument.
E.g.
def Max(myTuple):
first, second =
myTuple if
first>second:
return first
else:
return
r=(3,second
1) OUTPUT
m=Max(r) 3
print(m)
PASS DICTIONARY TO A FUNCTION

In Python, everything is an object, so the dictionary


can be passed as an argument to a function like
other variables are passed.
def func(d):
for key in
d:
print("key:"
, key, code
# Driver's OUTPUT
Mydict"Value:",
= {'a':1, 'b':2, 'c':3} key: a Value: 1
d[key])
func(Mydict) key: b Value: 2
key: c Value:
3

You might also like