0% found this document useful (0 votes)
5 views25 pages

7.Functions in Python

The document provides a comprehensive overview of functions in Python, detailing their types, syntax, and usage. It covers built-in and user-defined functions, parameters, return statements, and various types of arguments, including positional, keyword, default, and variable-length arguments. Additionally, it discusses global and local variables, recursive functions, anonymous functions (lambda), and the use of filter and map functions with examples.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views25 pages

7.Functions in Python

The document provides a comprehensive overview of functions in Python, detailing their types, syntax, and usage. It covers built-in and user-defined functions, parameters, return statements, and various types of arguments, including positional, keyword, default, and variable-length arguments. Additionally, it discusses global and local variables, recursive functions, anonymous functions (lambda), and the use of filter and map functions with examples.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Leela Soft Python Madhu

Functions in Python
Functions:
If a group of statements is repeatedly required then it is not recommended to write these
statements every time separately.

We have to define these statements as a single unit and we can call that unit any number of
times based on our requirement without rewriting. This unit is nothing but function.

The main advantage of functions is code Reusability.

Note: In other languages functions are known as methods, procedures, subroutines etc.

Python supports 2 types of functions:


✓ Built in Functions
✓ User Defined Functions

1. Built in Functions:
The functions which are coming along with Python software automatically, are called built in
functions or pre-defined functions

Examples: id(), type(), input(), eval(), etc..

2. User Defined Functions:


The functions which are developed by programmer explicitly according to business
requirements, are called user defined functions.

Syntax to create user defined functions:


def function_name(parameters):
"""doc string"""
;;;;;;;;
;;;;;;;;
return <value>

Note: While creating functions we can use 2 keywords


✓ def (mandatory)
✓ return (optional)

Example 1: Write a function to print Hello


test.py:
def wish():
print("Hello Good Morning")

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu

wish()
wish()
wish()

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.

Example: Write a function to take name of the student as input and print wish message by
name.
def wish(name):
print("Hello", name, " Good Morning")

wish("Madhu")
wish("Leela")

Example: Write a function to take number as input and print its square value
def squareIt(number):
print("The Square of", number, "is", number*number)

squareIt(4)
squareIt(5)

Return Statement:
Function can take input values as parameters and executes business logic, and returns output
to the caller with return statement.

Q. Write a function to accept 2 numbers as input and return sum.


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

result=add(10,20)
print("The sum is", result)
print("The sum is", add(100,200))

If we are not writing return statement then default return value is None
Example:
def f1():
print("Hello")
f1()
print(f1())

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu

Q. Write a function to check whether the given number is even or odd?


def even_odd(num):
if num%2==0:
print(num,"is Even Number")
else:
print(num,"is Odd Number")

even_odd(10)
even_odd(15)

Q. Write a function to find factorial of given number?


def fact(num):
result=1
while num>=1:
result=result*num
num=num-1
return result

for i in range(1,5):
print("The Factorial of",i,"is :",fact(i))

Returning multiple values from a function:


In other languages like C, C++ and Java, function can return at most one value. But in Python, a
function can return any number of values.

Example:
def sum_sub(a,b):
sum=a+b
sub=a-b
return sum,sub

x,y=sum_sub(100,50)
print("The Sum is :",x)
print("The Subtraction is :",y)

Example:
def calc(a,b):
sum=a+b
sub=a-b
mul=a*b
div=a/b

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu

return sum,sub,mul,div

t=calc(100,50)
print("The Results are",type(t))
for i in t:
print(i)

Types of arguments:
def f1(a,b):
;;;;;;;
;;;;;;;

f1(10,20) #Here, a and b are formal arguments whereas 10, 20 are actual arguments

There are 4 types are actual arguments are allowed in Python.


1. Positional arguments
2. Keyword arguments
3. Default arguments
4. Variable length arguments

1. Positional Arguments:
✓ These are the arguments passed to function in correct positional order.
✓ 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 an error.

def sub(a,b):
print(a-b)

sub(100,200)
sub(200,100)

2. keyword arguments:
✓ We can pass argument values by keyword that is by parameter name.

def wish(name,msg):
print("Hello",name,msg)

wish(name="Madhu", msg="Good Morning")


wish(msg="Good Morning", name="Madhu")

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu

Here the order of arguments is not important but number of arguments must be matched.

Note:
We can use both positional and keyword arguments simultaneously. But first we have to take
positional arguments and then keyword arguments, otherwise we will get syntax error.

def wish(name,msg):
print("Hello",name,msg)

wish("Madhu","GoodMorning") #==>valid
wish("Madhu",msg="GoodMorning") #==>valid
wish(name="madhu","GoodMorning") #==>invalid
#SyntaxError: positional argument follows keyword argument

3. Default Arguments:
Sometimes we can provide default values for our positional arguments

Example:
def wish(name="Guest"):
print("Hello",name,"Good Morning")

wish("Madhu")
wish() #If we are not passing any name then only default value will be considered.

Note: After default arguments we should not take non default arguments
def wish(name="Guest",msg="Good Morning"): #Valid
def wish(name,msg="Good Morning"): #Valid
def wish(name="Guest",msg): #Invalid
SyntaxError: non-default argument follows default argument

4. Variable length arguments:


Sometimes we can pass variable number of arguments to our function, such type of arguments
are called variable length arguments.
We can declare a variable length argument with * symbol as follows:

def f1(*n):

We can call this function by passing any number of arguments including zero number. Internally
all these values are represented in the form of tuple.

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu

Example:
def sum(*n):
total=0
for n1 in n:
total=total+n1
print("The Sum=",total)

sum()
sum(10)
sum(10,20)
sum(10,20,30,40)

Note: We can mix variable length arguments with positional arguments.

Example:
def f1(n1,*s):
print(n1)
for s1 in s:
print(s1)

f1(10)
f1(10,20,30,40)
f1(10,"A",30,"B")

Note: After variable length argument, if we are taking any other arguments then we should
provide values as keyword arguments

Example:
def f1(*s,n1):
for s1 in s:
print(s1)
print(n1)

f1("A","B",n1=10)

f1("A","B",10) #Invalid
TypeError: f1() missing 1 required keyword-only argument: 'n1'

Note: We can declare key word variable length arguments also. For this we have to use **.

def f1(**n):

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu

We can call this function by passing any number of keyword arguments. Internally these
keyword arguments will be stored inside a dictionary.

Example:
def display(**kwargs):
for k,v in kwargs.items():
print(k,"=",v)

display(n1=10,n2=20,n3=30)
display(rno=100, name="Madhu", marks=70, subject="Java")

Case Study:
def f(arg1,arg2,arg3=4,arg4=8):
print(arg1,arg2,arg3,arg4)

1. f(3,2) ==> 3 2 4 8
2. f(10,20,30,40) ===>10 20 30 40
3. f(25,50,arg4=100) ==>25 50 4 100
4. f(arg4=2,arg1=3,arg2=4)===>3 4 4 2
5. f()===>Invalid
TypeError: f() missing 2 required positional arguments: 'arg1' and 'arg2'

6. f(arg3=10,arg4=20,30,40) ==>Invalid
SyntaxError: positional argument follows keyword argument
[After keyword arguments we should not take positional arguments]

7. f(4,5,arg2=6)==>Invalid
TypeError: f() got multiple values for argument 'arg2'

8. f(4,5,arg3=5,arg5=6)==>Invalid
TypeError: f() got an unexpected keyword argument 'arg5'
Function vs. Module vs. Library:
✓ A group of lines with some name is called a function
✓ A group of functions saved to a file, is called Module
✓ A group of Modules is nothing but Library

Types of Variables:
Python supports 2 types of variables.
✓ Global Variables
✓ Local Variables

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu

1. Global Variables
✓ The variables which are declared outside of function are called global variables.
✓ These variables can be accessed in all functions of that module.

Example:
a=10 # global variable
def f1():
print(a)

def f2():
print(a)

f1()
f2()

2. Local Variables:
✓ The variables which are declared inside a function are called local variables.
✓ Local variables are available only for the function in which we declared it that is from
outside of function we cannot access.

Example:
def f1():
a=10
print(a) # valid

def f2():
print(a) #invalid

f1()
f2()

The global keyword:


We can use global keyword for the following 2 purposes:
✓ To declare global variable inside function
✓ To make global variable available to the function so that we can perform required
modifications

Example: 1
a=10
def f1():
a=777

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu

print(a)

def f2():
print(a)

f1()
f2()

Example: 2
a=10
def f1():
global a
a=777
print(a)

def f2():
print(a)

f1()
f2()

Example: 3
def f1():
a=10
print(a)

def f2():
print(a)

f1()
f2() #NameError: name 'a' is not defined

Example: 4
def f1():
global a
a=10
print(a)

def f2():
print(a)

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu

f1()
f2()

Note: If global variable and local variable having the same name then we can access global
variable inside a function as follows:

Example:
a=10 #global variable
def f1():
a=777 #local variable
print(a)
print(globals()['a'])

f1()

Recursive Functions:
A function that calls itself is known as Recursive Function.

Example:
factorial(3) = 3*factorial(2)
= 3*2*factorial(1)
= 3*2*1*factorial(0)
= 3*2*1*1
= 6
factorial(n) = n*factorial(n-1)

The main advantages of recursive functions are:


✓ We can reduce length of the code and improves readability
✓ We can solve complex problems very easily.

Q. Write a Python Function to find factorial of given number with recursion.


Example:
def factorial(n):
if n==0:
result=1
else:
result=n*factorial(n-1)
return result

print("Factorial of 4 is :",factorial(4))
print("Factorial of 5 is :",factorial(5))

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu

Anonymous Functions:
Sometimes we can declare a function without any name, such type of nameless functions are
called anonymous functions or lambda functions.

The main purpose of anonymous function is just for instant use (i.e for one time usage).

Normal Function:
We can define by using def keyword.
def squareIt(n):
return n*n

The lambda Function:


We can define by using lambda keyword.
lambda n:n*n

Syntax of lambda Function:


lambda argument_list : expression

Note:
By using Lambda Functions we can write very concise code so that readability of the program
will be improved.

Q. Write a program to create a lambda function to find square of given number?


s=lambda n:n*n
print("The Square of 4 is :",s(4))
print("The Square of 5 is :",s(5))

Q. Lambda function to find sum of 2 given numbers:


s=lambda a,b:a+b
print("The Sum of 10,20 is:",s(10,20))
print("The Sum of 10,20 is:",s(100,200))

Q. Lambda Function to find biggest of given values.


s=lambda a,b:a if a>b else b
print("The Biggest of 10,20 is:",s(10,20))
print("The Biggest of 100,200 is:",s(100,200))

Note:
Lambda Function internally returns expression value and we are not required to write return
statement explicitly.

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu

Note:
Sometimes we can pass function as argument to another function. In such cases lambda
functions are best choice.

We can use lambda functions very commonly with filter(),map() and reduce() functions,
because these functions expect function as argument.

filter() function:
We can use filter() function to filter values from the given sequence based on some
condition.

filter(function, sequence)

Here, function argument is responsible to perform conditional check and sequence can be list
or tuple or string.

Q. Program to filter only even numbers from the list by using filter() function?
Without lambda Function:
def isEven(x):
if x%2==0:
return True
else:
return False

l=[0,5,10,15,20,25,30]
l1=list(filter(isEven,l))
print(l1) #[0,10,20,30]

With lambda Function:


l=[0,5,10,15,20,25,30]

l1=list(filter(lambda x:x%2==0,l))
print(l1) #[0,10,20,30]

l2=list(filter(lambda x:x%2!=0,l))
print(l2) #[5,15,25]

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu

map() function:
For every element present in the given sequence, apply some functionality and generate new
element with the required modification. For this requirement we should go for map()
function.

Example: For every element present in the list perform double and generate new list of
doubles.

Syntax:
map(function, sequence)
The function can be applied on each element of sequence and generates new sequence.

Example: Without lambda


l=[1,2,3,4,5]

def doubleIt(x):
return 2*x

l1=list(map(doubleIt,l))
print(l1) #[2, 4, 6, 8, 10]

Example: with lambda


l=[1,2,3,4,5]

l1=list(map(lambda x:2*x,l))
print(l1) #[2, 4, 6, 8, 10]

Example 2: To find square of given numbers


l=[1,2,3,4,5]

l1=list(map(lambda x:x*x,l))
print(l1) #[1, 4, 9, 16, 25]

We can apply map() function on multiple lists also. But make sure all list should have same
length.

Syntax: map(lambda x,y:x*y,l1,l2))

Here, x is from l1 and y is from l2

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu

Example:
l1=[1,2,3,4]
l2=[2,3,4,5]
l3=list(map(lambda x,y:x*y,l1,l2))
print(l3) #[2, 6, 12, 20]

reduce() function:
The reduce() function reduces sequence of elements into a single element by applying the
specified function.

reduce(function, sequence)

The reduce() function present in functools module and hence we should write import
statement to import that module.

Example:
from functools import *

l=[10,20,30,40,50]
result=reduce(lambda x,y:x+y,l)
print(result) # 150

Example:
from functools import *

l=[10,20,30,40,50]
result=reduce(lambda x,y:x*y,l)
print(result) #12000000

Example:
from functools import *

result=reduce(lambda x,y:x+y,range(1,101))
print(result) #5050

Note:
✓ In Python everything is treated as object.
✓ Even functions also internally treated as objects only.

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu

Example:
def f1():
print("Hello")

print(f1)
print(id(f1))

Function Aliasing:
For the existing function we can give another name, which is nothing but function aliasing.

Example:
def wish(name):
print("Good Morning:",name)

greeting=wish
print(id(wish))
print(id(greeting))

greeting('Madhu Sudhana')
wish('Madhu Sudhana')

Note: In the above example only one function is available but we can call that function by using
either wish name or greeting name.

If we delete one name still we can access that function by using alias name.

Example:
def wish(name):
print("Good Morning:",name)

greeting=wish
greeting('Madhu')
wish('Madhu')
del wish
#wish('Madhu') ==>NameError: name 'wish' is not defined
greeting('Pavan')

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu

Nested Functions:
We can declare a function inside another function, such type of functions are called Nested
functions.

Example:
def outer():
print("outer function started")

def inner():
print("inner function execution")

print("outer function calling inner function")


inner()

outer()
#inner() #NameError: name 'inner' is not defined

In the above example inner() function is local to outer() function and hence it is not possible
to call directly from outside of outer() function.

Note: A function can return another function.

Example:
def outer():
print("outer function started")

def inner():
print("inner function execution")

print("outer function returning inner function")


return inner

f1=outer()
f1()
f1()
f1()

Q. What is the difference between the following lines?


✓ f1 = outer
✓ f1 = outer()

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu

In the first case for the outer() function we are providing another name f1(function aliasing).

But in the second case we calling outer() function, which returns inner function. For that
inner function() we are providing another name f1.

Note: We can pass function as argument to another function

Examples:
✓ filter(function, sequence)
✓ map(function, sequence)
✓ reduce(function, sequence)

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu

Function Decorators:
Decorator is a function which can take a function as argument and extend its functionality and
returns modified function with extended functionality.

The main objective of decorator functions is we can extend the functionality of existing
functions without modifies that function.

def wish(name):
print("Hello",name,"Good Morning")

This function can always print same output for any name
Hello Madhu Good Morning
Hello Leela Good Morning
Hello Uma Good Morning

But we want to modify this function to provide different message if name is Uma. We can do
this without touching wish() function by using decorator.

def decor(func):
def inner(name):
if name=="Uma":
print("Hello Uma Morning")
else:
func(name)
return inner

@decor
def wish(name):
print("Hello",name,"Good Morning")

wish("Madhu")
wish("Leela")
wish("Uma")

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu

In the above program whenever we call wish() function automatically decor function will be
executed.

How to call same function with decorator and without decorator:


We should not use @decor
def decor(func):
def inner(name):
if name=="Uma":
print("Hello Uma Morning")
else:
func(name)
return inner

def wish(name):
print("Hello",name,"Good Morning")

decorfunction=decor(wish)
wish("Madhu") #decorator wont be executed
wish("Uma") #decorator wont be executed
decorfunction("Madhu")#decorator will be executed
decorfunction("Uma")#decorator will be executed

Example: 2
def smart_division(func):
def inner(a,b):
print("We are dividing",a,"with",b)
if b==0:
print("OOPS...cannot divide")
return
else:
return func(a,b)

return inner

@smart_division
def division(a,b):
return a/b

print(division(20,2))
print(division(20,0))

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu

Without decorator we will get Error. In this case output is:


ZeroDivisionError: division by zero

With decorator we won't get any error. In this case output is:
We are dividing 20 with 2
10.0
We are dividing 20 with 0
OOPS...cannot divide
None

Decorator Chaining
We can define multiple decorators for the same function and all these decorators will form
Decorator Chaining.

Example:
@decor1
@decor
def num():

For num() function we are applying 2 decorator functions. First inner decorator will work and
then outer decorator.

Example:
def decor1(func):
def inner():
x=func()
return x*x
return inner

def decor(func):
def inner():
x=func()
return 2*x
return inner

@decor1
@decor
def num():
return 10

print(num())

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu

Demo Program for decorator chaining:


def decor(func):
def inner(name):
print("First Decor(decor) Function Execution")
func(name)
return inner

def decor1(func):
def inner(name):
print("Second Decor(decor1) Execution")
func(name)
return inner

@decor1
@decor
def wish(name):
print("Hello",name,"Good Morning")

wish("Madhu")

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu

Generators:
✓ Generator is a function which is responsible to generate a sequence of values.
✓ We can write generator functions just like ordinary functions, but it uses yield
keyword to return values.

Example:
def mygen():
yield 'A'
yield 'B'
yield 'C'

g=mygen()
print(type(g))

print(next(g))
print(next(g))
print(next(g))
print(next(g))

Output:
<class 'generator'>
A
B
C
Traceback (most recent call last):
File "C:\Users\LEELASOFT\py\test.py", line 12, in <module>
print(next(g))
StopIteration

Example:
def countdown(num):
print("Start Countdown")
while(num>0):
yield num
num=num-1

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu

values=countdown(5)
for x in values:
print(x)

Example 3: To generate first n numbers:


def firstn(num):
n=1
while n<=num:
yield n
n=n+1

values=firstn(5)
for x in values:
print(x)

We can convert generator into list as follows:


values=firstn(10)
l1=list(values)
print(l1) #[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Example 4: To generate Fibonacci Numbers


The next is the sum of previous 2 numbers
Ex: 0,1,1,2,3,5,8,13,21,...

def fib():
a,b=0,1
while True:
yield a
a,b=b,a+b

for f in fib():
if f>100:
break
print(f)

Advantages of Generator Functions:


✓ When compared with class level Iterators, generators are very easy to use
✓ Improves memory utilization and performance.

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu

✓ Generators are best suitable for reading data from large number of large files
✓ Generators work great for web scraping and crawling

Generators vs Normal Collections w.r.t performance


import random
import time

names = ['Sunny','Bunny','Chinny','Vinny']
subjects = ['Python','Java','Blockchain']

def people_list(num_people):
results = []
for i in range(num_people):
person = {
'id':i,
'name': random.choice(names),
'subject':random.choice(subjects)
}
results.append(person)
return results

def people_generator(num_people):
for i in range(num_people):
person = {
'id':i,
'name': random.choice(names),
'major':random.choice(subjects)
}
yield person

'''t1 = time.clock()
people = people_list(10000000)
t2 = time.clock()'''
t1 = time.clock()
people = people_generator(10000000)
t2 = time.clock()
print('Took {}'.format(t2-t1))

Note: In the above program observe the difference w.r.t execution time by using list and
generators

www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu

Generators vs Normal Collections with respect to Memory Utilization:


Normal Collection:
l=[x*x for x in range(10000000000000000)]
print(l[0])

We will get MemoryError in this case because all these values are required to store in the
memory.

Generators:
g=(x*x for x in range(10000000000000000))
print(next(g))

Output: 0
We won't get any MemoryError because the values won't be stored at the beginning

www.leelasoft.com Cell: 78 42 66 47 66

You might also like