Chapter 10 Python
Chapter 10 Python
*****************Chapter-10********************
………………………………………………………………………………………
******************FUNCTIONS*******************
……………………………………………………………………………………..
->If a group of statements is repeatedly required then it
is not recommended to write these statements
everytime seperately.
->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
1. Built in Functions
2. 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
Eg:
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.
1) def wish():
2) print("Hello Good Morning")
3) wish()
4) wish()
5) 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,otherwise we will get error.
1. def wish(name):
2. print("Hello",name," Good Morning")
3. wish("prasanna")
4. wish("Ravi")
5.
6.
7. D:\Python_classes>py test.py
8. Hello prasanna Good Morning
9. Hello Ravi Good Morning
…………………………………………………………………………………..
Eg: Write a function to take number as input and print its
square value
1. def squareIt(number):
2. print("The Square of",number,"is", number*number)
3. squareIt(4)
4. squareIt(5)
5.
6. D:\Python_classes>py test.py
7. The Square of 4 is 16
8. The Square of 5 is 25
………………………………………………………………………………………
***************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.
1. def add(x,y):
2. return x+y
3. result=add(10,20)
4. print("The sum is",result)
5. print("The sum is",add(100,200))
6.
7.
8. D:\Python_classes>py test.py
9. The sum is 30
10. The sum is 300
1. def f1():
2. print("Hello")
3. f1()
4. print(f1())
5.
6. Output
7. Hello
8. Hello
9. None
………………………………………………………………………………….
Q. Write a function to check whether the given number is
even or odd?
1. def even_odd(num):
2. if num%2==0:
3. print(num,"is Even Number")
4. else:
5. print(num,"is Odd Number")
6. even_odd(10)
7. even_odd(15)
8.
9. Output
10. D:\Python_classes>py test.py
11. 10 is Even Number
12. 15 is Odd Number
……………………………………………………………………………………….
*******Returning multiple values from a function:***:-
………………………………………………………………………………………
In other languages like C,C++ and Java, function can
return atmost one value. But in Python, a function can
return any number of values.
……………………………………………………………………………..
Eg 1:
1) def sum_sub(a,b):
2) sum=a+b
3) sub=a-b
4) return sum,sub
5) x,y=sum_sub(100,50)
6) print("The Sum is :",x)
7) print("The Subtraction is :",y)
8)
9) Output
10) The Sum is : 150
11) The Subtraction is : 50
……………………………………………………………………………
Eg 2:
1) def calc(a,b):
2) sum=a+b
3) sub=a-b
4) mul=a*b
5) div=a/b
6) return sum,sub,mul,div
7) t=calc(100,50)
8) print("The Results are")
9) for i in t:
10) print(i)
11)
12) Output
13) The Results are
14) 150
15) 50
16) 5000
17) 2.0
……………………………………………………………………………………
*************Types of arguments:-***********
…………………………………………………………………………………….
def f1(a,b): ------
------------
f1(10,20)
1. positional arguments
2. keyword arguments
3. default arguments
4. Variable length arguments
…………………………………………………………………………………..
1. positional arguments:
sub(100,200)
sub(200,100)
Eg:
1. def wish(name,msg):
2. print("Hello",name,msg)
3. wish(name=" prasanna ",msg="Good Morning")
4. wish(msg="Good Morning",name=" prasanna ")
5.
6. Output
7. Hello prasanna Good Morning
8. Hello prasanna Good Morning
def wish(name,msg):
print("Hello",name,msg)
wish("prasanna ","GoodMorning") ==>valid
wish(“prasanna ",msg="GoodMorning") ==>valid
wish(name=" prasanna ","GoodMorning") ==>invalid
SyntaxError: positional argument follows keyword
argument
………………………………………………………………………………………
3. Default Arguments:
Sometimes we can provide default values for our
positional arguments.
Eg:
1) def wish(name="Guest"):
2) print("Hello",name,"Good Morning")
3)
4) wish("prasanna ")
5) wish()
6)
7) Output
8) Hello prasanna Good Morning
9) Hello Guest Good Morning
………………………………………………………………………………………
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
Eg:
1) def sum(*n):
2) total=0
3) for n1 in n:
4) total=total+n1
5) print("The Sum=",total)
6)
7) sum()
8) sum(10)
9) sum(10,20)
10) sum(10,20,30,40)
11)
12) Output
13) The Sum= 0
14) The Sum= 10
15) The Sum= 30
16) The Sum= 100
---------------------------------------------------------------------------
Note:
->We can mix variable length arguments with positional
arguments.
……………………………………………………………
Eg:
………………………………..
1) def f1(n1,*s):
2) print(n1)
3) for s1 in s:
4) print(s1)
5)
6) f1(10)
7) f1(10,20,30,40)
8) f1(10,"A",30,"B")
9)
10) Output
11) 10
12) 10
13) 20
14) 30
15) 40
16) 10
17) A
18) 30
19) B
………………………………………………………………………………….
->Note: After variable length argument,if we are taking
any other arguments then we should provide values as
keyword arguments.
………………………………………………………..
Eg:
1) def f1(*s,n1):
2) for s1 in s:
3) print(s1)
4) print(n1)
5)
6) f1("A","B",n1=10)
7) Output
8) A
9) B
10) 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):
---------------------------------------------------------------------------
->We can call this function by passing any number of
keyword arguments. Internally these keyword arguments
will be stored inside a dictionary.
………………………………………………………………………………………
Eg:
1) def display(**kwargs):
2) for k,v in kwargs.items():
3) print(k,"=",v)
4) display(n1=10,n2=20,n3=30)
5)display(rno=100,name=" prasanna
",marks=70,subject="Jav a")
6)
…………………………………………………………………………….
7) Output
8) n1 = 10
9) n2 = 20
10) n3 = 30
11) rno = 100
12) name = prasanna
13) marks = 70
14) 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
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
7. f(4,5,arg2=6)==>Invalid
TypeError: f() got multiple values for argument 'arg2'
8. f(4,5,arg3=5,arg5=6)==>Invalid
Eg:
1) a=10 # global variable
2) def f1():
3) print(a)
4)
5) def f2():
6) print(a)
7)
8) f1()
9) f2()
10)
11) Output
12) 10
13) 10
……………………………………………………………………………..
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.i.e from outside of function we
cannot access.
………………………………………………………………..
Eg:
1) def f1():
2) a=10
3) print(a) # valid
4)
5) def f2():
6) print(a) #invalid
7)
8) f1()
9) f2()
10)
11) NameError: name 'a' is not defined
……………………………………………………………………………………
global keyword:
……………………………………………………………………….
We can use global keyword for the following 2 purposes:
1) def f1():
2) a=10
3) print(a)
4)
5) def f2():
6) print(a)
7)
8) f1()
9) f2()
10)
11) NameError: name 'a' is not defined
………………………………………………………………………….
Eg 4:
………………………………….
1) def f1():
2) global a
3) a=10
4) print(a)
5)
6) def f2():
7) print(a)
8)
9) f1()
10) f2()
11)
12) Output
13) 10
14) 10
………………………………………………………………………………………
Note: If global variable and local variable having the
same name then we can access global variable inside a
function as follows.
1)def factorial(n):
2) if n==0:
3) result=1
4) else:
5) result=n*factorial(n-1)
6) return result
7) print("Factorial of 4 is :",factorial(4))
8) print("Factorial of 5 is :",factorial(5))
9)
10) Output
11) Factorial of 4 is : 24
12) Factorial of 5 is : 120
…………………………………………………………………………………….
Anonymous Functions:-
……………………………………………………………………………………….
->Sometimes we can declare a function without any
name,such type of nameless functions are called
anonymous functions or lambda functions.
1) s=lambda n:n*n
2) print("The Square of 4 is :",s(4))
3) print("The Square of 5 is :",s(5))
4)
5) Output
6) The Square of 4 is : 16
7) The Square of 5 is : 25
………………………………………………………………………………………
Q. Lambda function to find sum of 2 given numbers
1) s=lambda a,b:a+b
2) print("The Sum of 10,20 is:",s(10,20))
3) print("The Sum of 100,200 is:",s(100,200))
4)
5) Output
6) The Sum of 10,20 is: 30
7) The Sum of 100,200 is: 300
…………………………………………………………………………….
Q. Lambda Function to find biggest of given values.
1) s=lambda a,b:a if a>b else b
2) print("The Biggest of 10,20 is:",s(10,20))
3) print("The Biggest of 100,200 is:",s(100,200))
4)
5) Output
6) The Biggest of 10,20 is: 20
7) The Biggest of 100,200 is: 200
………………………………………………………………………………….
Note:-
…………………………………………………………………..
Lambda Function internally returns expression value and
we are not required to write return statement explicitly.
………………………………………………………………………….
Note: Sometimes we can pass function as argument to
another function. In such cases lambda functions are
best choice.
1) def isEven(x):
2) if x%2==0:
3) return True
4) else:
5) return False
6) l=[0,5,10,15,20,25,30]
7) l1=list(filter(isEven,l))
8) print(l1) #[0,10,20,30]
………………………………………………………………………………
with lambda Function:
1) l=[0,5,10,15,20,25,30]
2) l1=list(filter(lambda x:x%2==0,l))
3) print(l1) #[0,10,20,30]
4) l2=list(filter(lambda x:x%2!=0,l))
5) print(l2) #[5,15,25]
…………………………………………………………………………….
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.
1) l=[1,2,3,4,5]
2) def doubleIt(x):
3) return 2*x
4) l1=list(map(doubleIt,l))
5) print(l1) #[2, 4, 6, 8, 10]
…………………………………………………………………………………..
with lambda:-
………………………………..
1) l=[1,2,3,4,5]
2) l1=list(map(lambda x:2*x,l))
3) print(l1) #[2, 4, 6, 8, 10]
-------------------------------------------------------------
Eg 2: To find square of given numbers
1. l=[1,2,3,4,5]
2. l1=list(map(lambda x:x*x,l))
3. 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))
x is from l1 and y is from l2
Eg:
1. l1=[1,2,3,4]
2. l2=[2,3,4,5]
3. l3=list(map(lambda x,y:x*y,l1,l2))
4. print(l3) #[2, 6, 12, 20]
……………………………………………………………………………………..
reduce() function:
…………………………………………………..
reduce() function reduces sequence of elements into a
single element by applying the specified function.
…………………………………………………………………………….
reduce(function,sequence)
1) def f1():
2) print("Hello")
3) print(f1)
4) print(id(f1))
Output
<function f1 at 0x00419618>
4298264
…………………………………………………………………………………..
Function Aliasing:
………………………………………………
For the existing function we can give another name,
which is nothing but function aliasing.
Eg:
1) def wish(name):
2) print("Good Morning:",name)
3)
4) greeting=wish
5) print(id(wish))
6) print(id(greeting))
7)
8) greeting('Prasanna')
9) wish('Prasanna')
…………………………………………………………………………
Output:-
4429336
4429336
Good Morning: Prasanna
Good Morning: Prasanna
…………………………………………………………………………….
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
………………………………………………….
Eg:
1) def wish(name):
2) print("Good Morning:",name)
3)
4) greeting=wish
5)
6) greeting('Prasanna')
7) wish('Prasanna')
8)
9) del wish
10) #wish('Prasanna') ==>NameError: name 'wish' is not
defined
11) greeting('Pavan')
…………………………………………………………………………
Output:-
Good Morning: Prasanna
Good Morning: Prasanna
Good Morning: Pavan
….…………………………………………………………….…………………….
……………………………………………………………………………………..
***********************END*******************
……………………………………………………………………………………