FUNCTIONS
PREPARED BY:
DR.M.N.KAVITHA
FUNCTION
• A function is a set of code that performs any given
task, enabling the programmer to modularize a
program
Benefits of functions
• High reusability
• Better modularity
• Easy to understand, code, test and maintain
• Reduces redundancy
TYPES OF FUNCTIONS
• BUILT-IN FUNCTIONS
The functions that are defined in the Python library are called
built-in or library functions or pre-defined functions
Eg: print(), input(), range()
• USER-DEFINED FUNCTIONS
The functions that are defined by the user to perform a particular
task is called user-defined functions
STEPS TO DEFINE A FUNCTION
• Use the def keyword with the function name to define a
function.
• Next, pass the number of parameters as per your requirement.
(Optional).
• Next, define the function body with a block of code. This block of
code is nothing but the action you wanted to perform.
• The indentation is essential to separate code blocks.
Local Variable vs Global Variable
• A local variable is a variable declared inside the function that is
not accessible from outside of the function. The scope of the
local variable is limited to that function only where it is declared.
• A Global variable is a variable that is defined in the main body of
the program. They are visible and accessible throughout the
program.
var = 20
def func1(): OUTPUT
loc_var = 10 Value of loc_var=10
Value of var=20
print("Value of loc_var=",
Value of var=20
loc_var)
print("Value of var=", var)
func1()
Local variable & Global variable
If we access a local variable outside the function, we get
NameError.
def func():
OUTPUT:
s = ’Good’
print(”In function, s=",s) In function, s= Good
func() NameError: name ‘s' is not
print("Outside function, defined
s=",s)
Using ‘global’ statement
To make the local variable defined inside a function as
global, use the ‘global’ statement.
def func():
OUTPUT:
global s
s = ’Good’ In function, s= Good
print(”In function, s=",s) Outside function, s=
func() Good
print("Outside function,
s=",s)
Local and Global variable with same name
• If the local variable is given the same name as of
global variable, then the local variable value is
used inside the function.
var=10
def func(): OUTPUT:
var=20
print("Inside function, Inside function, var=
var=",var) 20
func() Outside function,
print("Outside function, var= 10
var=",var)
Same variable names used in nested
functions
• If the same variable is used in both the outer and inner
functions, then the inner function uses the inner value
declared.
def out_func():
var=10 OUTPUT:
def in_func():
var=20 Inner function, var=
print("Inner function, 20
var=",var) Outer function, var=
in_func() 10
print("Outer function,
var=",var)
out_func()
Changing the values of global variables inside
functions
v='Happy' OUTPUT:
def show():
v = 'Good' In function, v= Good
Outside function, v=
print("In function, v=",v)
Happy
show()
print("Outside function,
v=",v)
v='Happy'
def show(): OUTPUT:
global v
v = 'Good' In function, v= Good
print("In function, v=",v) Outside function, v=
show() Good
print("Outside function, v=",v)
Variable name same for local & global
variables
def show():
OUTPUT:
print(v)
v = 'Good' UnboundLocalError: cannot
print(v) access local variable 'v' where
v='Happy' it is not associated with a value
show()
def show():
global v
print(v) OUTPUT:
v = 'Good' Happy
print(v) Good
v='Happy' Good
show()
print(v)
return statement
• In python, to return value from the function, a return
statement is used. It returns the value of the
expression following the returns keyword.
Syntax: return [Expression]
• The return value is nothing but a outcome of
function.
• The return statement ends the function execution.
• If a return statement is used without any expression,
OUTPUT:
then the None is returned.
• The return statement should be inside of the function
sum= 40
block.
return statement
The return value may or may not be assigned to another
variable in the call. The implicit return statement for a
function returns None
OUTPUT:
def show(str):
print(str)
Happy
x=show('Happy')
None
print(x)
Good
print(show('Good
Morning!
Morning!'))
None
FUNCTION TYPES BASED ON
ARGUMENTS & RETURN TYPE
FUNCTION WITHOUT ARGUMENTS AND WITHOUT
RETURN VALUE
FUNCTION WITHOUT ARGUMENTS AND WITH RETURN
VALUE
FUNCTION WITH ARGUMENTS AND WITHOUT RETURN
VALUE
FUNCTION WITHOUT ARGUMENTS &
WITHOUT RETURN VALUE
No return value
OUTPUT:
sum= 40
No arguments
passed
FUNCTION WITHOUT ARGUMENTS & WITH
RETURN VALUE
return value
OUTPUT:
sum= 40
No arguments
FUNCTION WITH ARGUMENTS & WITHOUT
RETURN VALUE
No return
value
OUTPUT:
sum= 40
Arguments
FUNCTION WITH ARGUMENTS & WITH
RETURN VALUE
return value
OUTPUT:
sum= 40
Arguments
EXAMPLE: FINDING GCD OF TWO NUMBERS
def gcd(a,b):
g=1 OUTPUT:
for i in range(1,min(a,b)+1):
Enter number1 12
if a%i==0 and b%i==0:
Enter number2 18
g=i GCD of 12 and 18 is
return g 6
m=int(input("Enter number1"))
n=int(input("Enter number2"))
g1=gcd(m,n)
print("GCD of {} and {} is
{}".format(m,n,g1))
PYTHON FUNCTION ARGUMENTS
• The argument is a value, a variable, or an object that
we pass to a function or method call. In Python, there
are four types of arguments allowed.
Positional arguments/Required
arguments
Keyword arguments
Default arguments
Variable-length arguments
POSITIONAL ARGUMENTS
• Positional arguments are arguments that are
pass to function in proper positional order.
Here a=50, b=10, the values are
mapped based on their position
Here a=10, b=50, the values are
mapped based on their position
POSITIONAL ARGUMENTS
• If you try to use pass more parameters you will
get an error.
In the positional argument,
number and position of arguments
must be matched. If we change
the order, then the result may
change. Also, If we change the
number of arguments, then we
will get an error.
KEYWORD ARGUMENTS
• Python allows functions to be called using keyword
arguments in which the order of the arguments can be
changed. The values are assigned based on their
name.
• Example: OUTPUT
KEYWORD ARGUMENTS
The values can be assigned based on their name.
Example:
OUTPUT
DEFAULT ARGUMENTS
• Default arguments take the default value during the function
call if we do not pass them. We can assign a default value to an
argument in function definition using the = assignment
operator.
• EXAMPLE
def message(name="Guest"): Output
print(“Welcome ", name)
message("John") # calling function with argument Welcome John
message() # calling function without argument Welcome Guest
VARIABLE-LENGTH ARGUMENTS
• In python, sometimes, there is a situation where we need to
pass multiple numbers of arguments to the function. Such
types of arguments are called variable-length arguments.
We can declare a variable-length argument with the *
(asterisk) symbol.
Syntax: def fun(*var):
function body
Example: def addition(*numbers):
total = 0 Output
for n in numbers:
total = total + n
print("Sum is:", total) Sum is: 0
Sum is: 26
addition() # 0 arguments
Sum is: 17.5
addition(10, 5, 2, 5, 4) # 5 arguments
addition(8, 7, 2.5) # 3 arguments
VARIABLE-LENGTH ARGUMENTS
• The variable-length arguments are formed as a
tuple before being passed to a function. A for loop
can be used to access the passed arguments in the
function definition.
• Any parameters written after the variable-length
arguments must be keyword arguments
def addition(*numbers, name): Output
print(‘Name=‘,name) Name=Alice
for i in numbers: 10
print(i) 20
addition(10,20,30,name=‘Alice’) 30
VARIABLE-LENGTH ARGUMENTS
If we don’t use keyword arguments after the variable-length
arguments, we get the error.
Exam
ple
def addition(*numbers, n): Output
print('Name=',n)
for i in numbers:
print(i)
addition(10,20,30,'Alice')
If we use formal arguments before the variable-length
arguments, we can avoid the errors.
def addition(n,*numbers):
print('Name=',n)
Output
for i in numbers: Name=Alice
print(i) 10
addition('Alice',10,20,30)
20
30
LAMBDA FUNCTIONS/ANONYMOUS
FUNCTIONS
• Lambda functions are not declared as other functions using def
keyword
• They are created using ‘lambda’ keyword, without any name
• lambda functions are syntactically restricted to a single
expression.
lambda arguments :
expression
Syntax:
The arguments contain a comma separated list of arguments and
var1 = lambda
the expression arguments
uses these :
arguments. The function can be
expression
assigned to a variable to give it a name.
LAMBDA FUNCTIONS/ANONYMOUS
FUNCTIONS
Example: OUTPUT:
sum = lambda x,y:
x+y Sum = 30
print(“Sum=“,sum(20
,10))
Here x, y are arguments; x+y is the expression that
gets evaluated and returned to the variable sum. It has
no name.
LAMBDA FUNCTIONS
Example: Using conditional statements with lambda
functions
OUTPUT:
big = lambda x,y: x if x>y
else y 20
print(big(20,10))
Here x, y are arguments; the expression is using if..else
construct to evaluate the result.
LAMBDA FUNCTIONS
Example: OUTPUT:
twice = lambda x: x *2
thrice = lambda x: x *3 6
print(twice(3)) 9
print(thrice(3))
16
print((lambda x: x * x)(4))
LAMBDA FUNCTIONS
Example: OUTPUT:
A=
lambda:sum(range(1,6)) 15
print(A())
range(1,6) 1,2,3,4,5
sum(range(1,6)) 1+2+3+4+5 = 15
Here lambda function don’t have any
arguments. range() and sum() built-in functions
LAMBDA FUNCTIONS
Example: Use of lambda functions with regular functions
def square(y):
return (lambda x : x*x)
OUTPUT:
(y)
a=10 a=10
print(“a=“,a) Square of a=100
b=square(a)
print(“Square of a=“,b)
Here lambda function is used inside a regular
function, square() to return the squared value.
NESTED LAMBDA FUNCTIONS
Example: Use of lambda functions within another lambda
functions
add = lambda x,y: x+y OUTPUT:
mul_add=lambda x,y,z: 27
add(x,y)*z
print(mul_add(5,4,3))
Here lambda function,add is used inside another
lambda function,mul_add
mul_add(5,4,3) add(5,4)*3 5+4*3 27
Arguments in lamda function
>>> (lambda x, y, z: x + y + z)(1, 2, 3)
#Output = 6
>>> (lambda x, y, z=3: x + y + z)(5, y=2)
#Output = 10
>>> (lambda *a: sum(a))(10,20,30)
#Output = 60