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

12.Functions

The document provides an extensive overview of functions in Python, including definitions, types (library and user-defined), and advantages such as code reusability and easier debugging. It details the syntax for defining functions, the use of parameters and return statements, as well as different types of arguments like positional, keyword, default, and variable-length arguments. Additionally, it covers advanced topics such as nested functions, recursion, anonymous functions (lambda), and the use of built-in functions like filter, map, and reduce.

Uploaded by

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

12.Functions

The document provides an extensive overview of functions in Python, including definitions, types (library and user-defined), and advantages such as code reusability and easier debugging. It details the syntax for defining functions, the use of parameters and return statements, as well as different types of arguments like positional, keyword, default, and variable-length arguments. Additionally, it covers advanced topics such as nested functions, recursion, anonymous functions (lambda), and the use of built-in functions like filter, map, and reduce.

Uploaded by

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

Functions :

Definition: - Function is a group of related statements that perform a specific


task.
Functions help to break our program into smaller parts that’s why debugging
of program is very easy.
It avoids repetition and makes code reusability.
Advantages of functions :
User-defined functions are reusable code blocks; they only need to be
written once, then they can be used multiple times.
These functions are very useful, from writing common utilities to specific
business logic.
The code is usually well organized, easy to maintain, and developer-
friendly.
A function can have different types of arguments & return value.
Functions can be divided into two types:
- Library functions
- User defined functions.
Library Functions: - The functions which are coming along with Python
software automatically are called built in functions or pre-defined functions.
Ex: id(), type(), input(), print()….

User defined Functions: - The functions which are developed by


programmer explicitly according to business requirements are called user
defined functions.
Syntax:
def functionname(parameters):
statements
return
def is a keyword to start function definition.
A function name is used to uniquely identify it. Function naming follows the
same rules of identifiers.
Write the arguments inside the opening and closing parentheses of the
function, and end the declaration with a colon.
Parameters (arguments) through which we pass values to a function. They
are optional.
return statement to return a value. return is optional.

Ex :

Ex: To specify no body of the function use pass statement.


def disp(): pass
disp()

Parameters: - Parameters are inputs to the function. If a function contains


parameters, then at the time of calling, compulsory we should provide values
otherwise we will get error.
Ex:
def wish(name):
print("Hello",name," Good morning")
wish("gangadhar")
Ex:
def square(number):
print("The square of ",number," is",number*number)
square(6)
Ex: One function is able to call more than one function.

def wish(name):

print("Hello",name," Good morning")

wish("gangadhar")

wish("lokesh")

Ex: def
happyBirthday(person):
print("Happy Birthday dear ",person)
def main():
happyBirthday('gangadhar')
happyBirthday('lokesh')

main()

return statement: - The return statement is used to exit a function and go


back to the place from where it was called.
return [expressionlist];
This statement can contain expression which gets evaluated and the value is
returned.
Example 1:
def addition(x,y):
return a+y

a,b=10,20
sum=addition(a ,b)
print(sum)

Ex:
def big(a,b):
if a>b:
return a
else:
return b

print(big(10,20))
print(big(50,40))

return statement is used to return multiple values.


Ex:
def cal(a,b):
sum=a+b
sub=a-b
mul=a*b
div=a/b
return sum,sub,mul,div
a,b,c,d=cal(10,2)
print("sum=",a)
print("sub=",b)
print("mul=",c)
print("div=",d)

Ex:
def cal(a,b):
sum=a+b
sub=a-b
mul=a*b
div=a/b
return sum,sub,mul,div
t=cal(10,2)
print("The results are:")
for i in t:
print(i)

If there is no expression in the statement or the return statement itself is not
present inside a function, then the function will return the None object.
Ex:
def wish(name):
print("Hello",name," Good morning")
wish("gangadhar")
wish("lokesh")
print(wish("ram"))

Types of arguments:
def f1(a,b):
-------
-------
f1(10,20)
a,b are formal arguments whereas 10,20 are actual arguments.
There are 4 types of actual arguments are allowed in Python.
1. Positional arguments.
2. Keyword arguments.
3. Default arguments.
4. Variable length arguments.

Positional arguments: - This is the default method. These are the arguments
passed to function in correct positional order.
Ex:
def cal(a,b):
s=a+b
return s
print(cal(100,10))
print(cal(100,100))

The number of arguments and position of arguments must be matched. If we


change the order then result may be changed.
If we change the number of arguments then we will get error.

Ex:
def add(a,b):
print(a+b)
add(10,20)
add(10.5,20.4)
add("gangadhar","babu")
add(10,10.5)
add("gangadhar",10)

Keyword Arguments: - The keywords are mentioned during the function call
along with their corresponding values. These keywords are mapped with the
function arguments so the function can easily identify the corresponding values
even if the order is not maintained during the function call.
Using the Keyword Argument, the argument passed in function call is matched
with function definition on the basis of the name of the parameter.
Ex:
def cal(a,b,c):
s=a+b+c
return s
print(cal(c=33,a=23,b=55))

Ex:
def msg(id,name):
print(id,name)
msg(id=111,name='gangadhar')
msg(name='anu',id=222)

Ex:
def disp(eid,ename):
print(eid,ename)

disp(eid=111,ename="anu")
disp(ename="ratan",eid=222)
disp(333,"durga")
disp(444,ename="sravya")
disp(eid=555,"aaa")
#SyntaxError: positional argument follows keyword argument

default: - Function arguments can have default values in Python. We can


provide a default value to an argument by using the equal operator.
Ex:
def cal(a=100,b=200,c=300) :
s=a+b+c
return s
print(cal(10,44,55))
print(cal())
print(cal(10))
print(cal(10,44))

Ex :
def empdetails(eid=1,ename="anu",esal=10000):
print ("Emp id =", eid)
print ("Emp name = ", ename)
print ("Empsal=", esal)
print("*********")

empdetails()
empdetails(222)
empdetails(333,"durga")
empdetails(111,"ratan",10.5)

ex :
def defArgFunc( empname, emprole = "Manager" ):
print ("Emp Name: ", empname)
print ("Emp Role ", emprole)

print("Using default value")


defArgFunc("Gangadhar")
print("************************")
print("Overwriting default value")
defArgFunc("Anu","CEO")

var-arg: -
var-arg means variable length argument.
Sometimes, we don’t know in advance the number of arguments that will be
passed into a function Python allows us to handle this type of situation
through function calls with arbitrary number of arguments.
In this function, we use “*” before the parameter. Ex:
def wish(*name):
for x in name:
print("Hello:",x)
wish('gangadhar', 'lokesh', 'rajesh')

Ex:
def disp(*var):
for i in var:
print("var arg=",i)
disp()
disp(10,20,30)
disp(10,20.3,"gangadhar")

Ex:
def sum(*a):
s=0
for x in a:
s=s+x
return s
print(sum(10,20))
print(sum(10,20,45,66))
print (sum())

 
We can mix positional arguments to var-arg
Ex:
def calc(x,*n):
s=0
for i in n:
s=s+i
print("x=",x,"sum=",s)
calc(10) calc(11,33,22,44,55))

We can mix keyword arguments to var-arg


Ex
def calc(**n):
print("The records are")
for k,v in n.items():
print(x,"……..",v)
calc(name='gangadhar',rno=100,marks=56)
calc(name='rajesh',rno=102,marks=86)

Types of variables:
Global variables: - A variable which is declared outside of the function or in
global scope is known as global variable. That means, global variable can be
accessed inside or outside of the function.
Ex:
def wish():
print("Inner:",x)

x=10
wish()
print("Outer:",x)
Local variables: - A variable which is declared inside the function body or in
a local scope is known as local variables. These variables are accessed
within the function.
Ex:
def f1():
y=10

print("Inner=",y
) f1() print("outer=",y)

NameError: name ‘y’ is not defined

global keyword: - global keyword allows to modify the variable


outside of the function.
Rules:
When we create a variable inside a function, it is local by default.
 When we define a variable outside a function, it is global by default.
We use global to read and write a global variable inside a function.
Use of global keyword outside a function has no effect.
Ex:
def wish():
global x
x=10
print("Inner x:",x)
wish()
print("Outer x:",x)

Nested functions: - A function declared inside another function is called as


nested function.
Ex:
def f1():
def inner(a,b):
print("The sum=",(a+b))
print("The avg=",(a+b)/2)
inner(10,20)
inner(45,55)
f1()

Similarly a function can return another function.


Ex:
def outer():
print("Outer part is executed")
def inner():
print("Inner part is executed")
print("Inner part is completed")
return inner;
f1=outer()
f1()
function aliasing
We can provide alias name for functions.
Ex:
r=range
for i in r(10):
print(i)
Ex:
def first(msg)
print(msg)

first("Hello")
s=first
s("Hai")
Recursive functions: -
A function called by itself is known as recursion.
It reduces length of the code and improves readability. We can solve complex
problems very easily.
Ex: Write a program for factorial of a given number
def fact(n): if n==0:
res=1
else: res=n*fact(n-1)
return res
print(fact(5)) print(fact(6))

Anonymous functions: - A function without having a name is called


anonymous function. These functions are used for instant use.
Syntax:
lambda input:expression

Ex:
s=lambda n:n*n
print(s(4))
print(s(6))

Normal functions are defined by using def keyword.


Anonymous functions are defined by using lambda keyword. That’s why
anonymous functions are also called as lambda functions.

Ex: Sum of two numbers using lambda


s=lambda a,b:a+b
print("sum =",s(10,200))

Ex: Biggest of two numbers


s=lambda a,b:a if a>b else b
print("biggest=",s(10,20))

Ex: Biggest of two numbers


s=lambda a,b:if a>b print(a,"is biggest") else print(b,"is biggest")
s(a,b)

A function can be passed as argument to another function.


Ex:
def inc(x):
return(x+1)

def dec(x)
return(x-1)

def operate(func,x)
res=func(x)
return res

print(operate(inc,10))
print(operate(dec,20))

Lambda is used for passing a function to an argument to another function.


Lambda functions are used along with built in functions like filter(), map(),
reduce() etc.

filter(): - This function takes a function and list as arguments. The function is
called with all the items in the list and new list is returned which contains
items for which the function evaluates true.
Syntax:
filter(function,sequence)
Ex:
def iseven(x):
if x%2==0:
return True
else:
return False

l=[10,8,5,12,13,11,10]
l2=list(filter(iseven,l))
print(l2)

Using lambda
l1=[10,8,5,12,13,11,10]
l2=list(filter(lambda x:x%2==0,l1))
print(l2)

map(): - This function takes a function and list as arguments. This function is
called with all the items in the list and a new list is returned which contains
items returned by that function for each item.
filter() and map() are same but filter() always displays checks True or False
but map() is used for business operations.
Syntax:
map(function,list)
Ex:
def square(x):
return x*x
l1=[10,8,5,12,13,11,10]
l2=list(map(square,l1))
print(l2)
with lambda
l1=[1,2,3,4,5]
l2=list(map(lambda x:x*x,l1))
print(l2)
Ex:
l1=[1,2,3,4]
l2=[10,20,30,40]
l3=list(map(lambda x,y:x*y,l1,l2))
print(l3)

reduce(): -
This function applies any sequence and returns a single value.
If sequence=[s1,s2,s3….sn], calling reduce as follows
At the first two elements of sequence will be applied to func, that is
func(s1,s2), the list on which reduce() works looks now like this
[func(s1,s2),s3…sn]
In the next step func will be applied on the previous result and the third
element of the list that is func(func(s1,s2),s3)
Continue like this until just one element is left and return this element as the
result reduce().

Syntax:
reduce(func,seq)

Ex:
from functools import reduce
print(reduce(lambda x,y:x+y,[45,66,77,88,99]))
45 66 77 88 99

111

188

276

375

Ex:
from functools import *
f=lambda a,b: a if a>b else b
print(reduce(f,[23,44,56,44,87,55]))
Ex:
from functools import *
print(reduce(lambda x,y:x+y,range(1,101)))

You might also like