Professional Documents
Culture Documents
Python Lec 4 - Functions, Modules, Decortors, Generators, Packages PDF
Python Lec 4 - Functions, Modules, Decortors, Generators, Packages PDF
Anand Komiripalem
Functions
A function is a set of statements that take inputs, do some specific
computation and produces output.
Function is a group of lines which can be reused.
In other languages functions are known as methods, procedures,
subroutines etc
Python supports 2 types of functions
Built in Functions
User Defined Functions
Built in Functions:
The functions which are coming along with Python software
automatically, are called built in functions or pre defined functions.
Ex: id(), type(), input(), eval() …….
Anand Komiripalem
Functions
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) :
“””Your code----
----- and logic”””
return value
Note: While creating functions we use 2 keywords
def (mandatory)
return (optional)
Anand Komiripalem
Functions
Write a function to print Hello
def wish():
print("Hello Good Morning")
Functions
Write a function to take number as input and print its square value:
def squareIt(x):
print("The Square of",number,"is", x*x)
squareIt(4) 16
squareIt(5) 25
def add(x,y):
return x+y
result=add(10,20)
print("The sum is",result) 30
print("The sum is",add(100,200)) 300
Anand Komiripalem
Functions
If we are not writing return statement then default return value is None.
def f1():
print("Hello")
f1() #Hello
print(f1()) #Hello
#Hello
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")
Functions
Write a Function to find Factorial of given Number?
def fact(num):
result=1
Output:
while num>=1: -----------
result=result*num
num=num-1 The Factorial of 1 is : 1
The Factorial of 2 is : 2
return result The Factorial of 3 is : 6
The Factorial of 4 is : 24
for i in range(1,5):
print("The Factorial of",i,"is :",fact(i))
Anand Komiripalem
Functions
Returning Multiple Values from a Function:
def sum_sub(a,b):
sum=a+b
Output
sub=a-b
return sum,sub The Sum is : 150
x,y=sum_sub(100,50) The Subtraction is : 50
print("The Sum is :",x)
print("The Subtraction is :",y)
Anand Komiripalem
Functions
Returning Multiple Values from a Function:
Ex 2:
def calc(a,b):
sum=a+b Output
sub=a-b
The Results are
mul=a*b 150
div=a/b 50
5000
return sum,sub,mul,div
2.0
t=calc(100,50)
print("The Results are")
for i in t:
print(i)
Anand Komiripalem
Functions
Types of Arguments:
There are 4 types of arguments allowed in Python.
Positional Arguments
Keyword Arguments
Default Arguments
Variable Length Arguments
Positional Arguments:
Variables will be assigned in what ever order we assign
def sub(a, b):
print(a-b)
sub(100, 200) #-100
sub(200, 100) #100
Number of parameters and arguments should be same or else we will
get error
Anand Komiripalem
Functions
Keyword Arguments:
Output:
Passing values by parameter name. ----------
def wish(name,msg):
Hello Anand Good Morning
print("Hello",name,msg)
Hello Anand Good Morning
wish(name=“Anand",msg="Good Morning")
wish(msg="Good Morning",name=“Anand")
Functions
def wish(name,msg):
print("Hello",name,msg)
wish(“Anand","GoodMorning") # Valid
wish(“Anand",msg="GoodMorning") # Valid
wish(name=“Anand”, msg=“Good Morning”) # Valid
wish(name="Durga","GoodMorning") #Invalid
Anand Komiripalem
Functions
Default Arguments:
we can provide default values for our positional arguments.
If we are not passing any arguments then only default value will
be considered.
def wish(name="Guest"):
print("Hello",name,"Good Morning")
wish(“Anand") #Hello Anand Good Morning
wish() #Hello Guest Good Morning
Functions
Variable Length Arguments:
Used for dynamically increasing the arguments
We can call this function by passing any number of arguments
including zero number.
def sum(*n):
total=0
for n1 in n:
total=total+n1
print("The Sum=",total)
Functions
We can mix variable length arguments with positional arguments.
If we want to take in this way then we need to pass the positional
arguments compulsorily
Ex:
def f1(n1,*s):
result=0
for x in s:
result=result+x
print(n1,”:”result)
f1(“anand”) #anand:0
f1(“anand”,10,20) #anand:30
Anand Komiripalem
Functions
After variable length argument, if we want to provide positional
argument then compulsorily we have to provide those values as
keyword arguments only
f1(n1=“anand”) #anand:0
f1(10,20, n1=“anand”) #anand:30
f1(10,20,“anand”) #Error
Anand Komiripalem
Functions
We can declare key word variable length in functions
We have to use **n for declaring key- value arguments
def display(**kwargs):
for k,v in kwargs.items():
print(k,"===",v)
display(rno=100,name=“anand", marks=70,subject="Java")
Output:
rno = 100
name = anand
marks = 70
subject = Java
Anand Komiripalem
Functions
Case Study:
def f(arg1,arg2,arg3=4,arg4=8):
print(arg1,arg2,arg3,arg4)
f(3,2) 3 2 4 8
f(10,20,30,40) 10 20 30 40
f(25,50,arg4=100) 25 50 4 100
f(arg4=2,arg1=3,arg2=4) 3442
f(arg3=10, arg4=20, 30, 40) SyntaxError: positional argument follows keyword argument
f(4, 5, arg2 = 6) TypeError: f() got multiple values for argument 'arg2'
f(4, 5, arg3 = 5, arg5 = 6) TypeError: f() got an unexpected keyword argument 'arg5‘
Anand Komiripalem
Functions:Types of Variables
Python supports 2 types of variables.
Global Variables
Local Variables
Global Variables :
The variables which are declared outside of function and are
available to all the functions in a module are global variables
a=10 # global variable
def f1():
print(a)
def f2():
print(a)
f1() #10
f2() #10
Anand Komiripalem
def f2():
print(a)
f1() #10
f2() #error
Anand Komiripalem
def f2():
print(a)
f1() #10
f2() #20
Anand Komiripalem
a=10
def f1():
global a
a=777
print(a)
def f2():
print(a)
f1() #777
f2() #777
Anand Komiripalem
a = 10 # Global Variable
def f1():
a=777 #Local Variable
print(a)
print(globals()['a'])
f1() #10
#777
Anand Komiripalem
def sumofn(n):
if n==1:
return 1
else:
return n + sumofn(n-1)
sumofn(16) #136
Anand Komiripalem
Ex:2
List_1 = [5, 10, 20, 30, 40, 'a', 'x', 50]
List_2 = [10, 40, 'a']
n_list = filter(lambda x: x not in List_2, List_1)
print(“New List: " ,list(n_list)) #[5,20,30,,x,50]
Anand Komiripalem
l=[1,2,3,4,5]
def doubleIt(x): l=[1,2,3,4,5]
return 2*x 2) l1=list(map(lambda x:2*x,l))
l1=list(map(doubleIt,l)) 3) print(l1) #[2, 4, 6, 8, 10]
print(l1) #[2, 4, 6, 8, 10]
Anand Komiripalem
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]
Anand Komiripalem
In the above example only one function is available but we can call that
function by using either wish name or greeting name.
Anand Komiripalem
def outer():
print("outer function started")
def inner():
print("inner function execution")
print("outer function returning inner function")
return inner
f1=outer Output:
f1() outer function started
outer function returning inner function
Anand Komiripalem
Modules
Anand Komiripalem
Modules
A group of functions, variables and classes saved to a file, which is
nothing but module.
Every Python file (.py) acts as a module.
def product(a,b):
print("The Product:",a*b)
Modules
If we want to use these variables and functions in other programs
then we need to import them by using “import” module
We can access members by using module name.
modulename.variable
modulename.function()
test.py:
Import mymath
print(mymath.x) #200
mymath.add(10,20) #30
mymath.product(10,20) #200
Anand Komiripalem
Modules
Advantages of Modules:
Code Reusability
Improved readability
Improved maintainability
Importing Modules:
Import modulename
from modulename import functions
Modules
Renaming a module @ time of importing: using aliasing (as)
Import mymath as m
print(m.x) #200
m.add(20,30) #50
m.product(10,20) #200
Once we create an alias name we need to use alias name only,
original name cannot be used, if we try to use the original name we
will get an error
Member Aliasing:
Modules
Reloading a Module:
By default module will be loaded only once even though we are importing
multiple times.
module1.py:
------------------
print("This is from module1")
test.py
----------
import module1 Output:
import module1
This is from module1
import module1
This is test module
import module1
print("This is test module")
Anand Komiripalem
Modules
We can solve this by reloading the module explicitly based on our
requirement
We can reload by using “reload ()” function of “imp” module
import imp
imp.reload(module 1)
Note: Normally import will load the module only once, but some times
while the program is running, the module might be updated and
those will not be reflected in the program. Inorder to apply those
changes in the program then we will need to reload the progam
Anand Komiripalem
Modules
Without reload function:
----------------------------------
import time
Output:
import module1
This is from module 1
print(“entering into sleep mode”) Entering into Sleep Mode
time.sleep(30) Last line printing
import module1
print(“last line printing”)
If we want to get the updated module every time we access it, then we
should go with “reload ” function
Anand Komiripalem
Modules
With reload function:
----------------------------------
import time
Output:
from imp import reload
import module1 This is from module 1
print(“entering into sleep mode”) Entering into Sleep Mode
This is from module 1
time.sleep(30)
Last line printing
reload(module1)
print(“last line printing”)
Anand Komiripalem
Modules
To find members of a module:
dir(): list all members of current module
dir(module_name): lists all members of specified module
Ex: dir(time) #[‘__doc__’, ‘__file__’, ‘__name__’………….]
Every python module will have some special properties for internal
usage which will be assigned at the time of creating the module
Modules
The Special Variable __name__:
Modules
multiply.py:
----------------
def mul(a,b):
return a*b
print(mul(5,4)) #20
Print(__name__) #__main__
xyz.py
--------- Output:
Import multiply
20
print(multiply.mul(2,3)) Multiply
print(__name__) 6
__main__
Anand Komiripalem
Modules
If we don’t want to print the conditions of a module in other programs
when the module is imported into other programs we should use
__name__ =__main__
multiply.py:
----------------
def mul(a,b):
return a*b
if __name__= __main__:
print(mul(5,4)) #20
Print(__name__) #__main__
xyz.py
---------
Import multiply
print(multiply.mul(2,3)) #6
print(__name__) #__main__
Anand Komiripalem
Modules
math module:
Inbulit module
To get functions available in math module use
import math
dir(math)
Ex:
from math import *
print(sqrt(4)) #2.0
print(pi) #3.1415
print(gcd(100,90)) #10
import random
import string
def randomString(strlength=10):
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(strlength))
import random
import string
def randomStringDigits(strlen=2):
lettersAndDigits = string.ascii_letters + string.digits
return ''.join(random.choice(lettersAndDigits) for i in range(strlen))
Output:
First Random String is bQZv8vhi
Second Random String is A8zo6Qdr
Third Random String is oqobjDO1
Anand Komiripalem
import random
import string
def randomS(strLen=10):
s = string.ascii_letters + string.digits + string.punctuation
return ''.join(random.choice(s) for i in range(strLen))
Output:
First Random String 8m@x%Nlyf[
Second Random String #mI?8wQ$NY
Third Random String z56orDN%ou
Anand Komiripalem
Decorator
Anand Komiripalem
Decorators
Decorator is a function by itself
Decorator accepts a input function and perform some operation on it
and provide the output function with an extended functionality
Decorators
In the above example If we want to display a different message to some
specific user with out effecting the original function we can go with
decorator
we can modify the above function to provide different message for a
specific user without touching wish() function by using decorator.
Decorators
In the above Example:
func is an argument which represents wish() function
@decor is annotation to call decorator function
Note: The argument and annotation can be any name of your choice
Decorators
We can call the same decorator without using the annotation by explicitly
declaring the decorator
def wish(name):
print("Hello", name, “GM")
def decorator(wish):
def inner(name):
dfunction=decorator(wish)
if name=="hari":
print("Hello hari u r worst")
wish("anand") #Hello anand GM
else:
wish("Ravi") #Hello Ravi GM
wish(name)
wish("hari") #Hello hari GM
return inner
dfunction("hari") #Hello hari ur worst
dfunction("raghu") #Hello raghu GM
Anand Komiripalem
Decorators
Ex:
def divn(div):
def mats(a,b):
if b==0:
print("not possible")
else:
print(div(a,b))
return(mats)
@divn
def div(a,b):
return a/b
div(10,2) #5.0
div(10,0) #not possible
div(3,6) #0.5
Anand Komiripalem
Decorators
Decorator Chaining : We can define multiple decorators for the same
function and all these decorators will form Decorator Chaining.
def decorator(wish):
def inner(name): @decorator
print("first decor execution") @decorator1
wish(name) def wish(name):
return inner print("hello",name,"Good Morning")
wish("anand")
def decorator1(wish):
def inner(name): Output:
print("second decor execution") first decor execution
wish(name) second decor execution
return inner hello anand Good Morning
Anand Komiripalem
Decorators
Inner décor will be executed first and the output of inner décor will
be given as input to the outer decorator
Ex-2:
def div1(num):
def inner():
n=num()
return n*n @div1
return inner @div2
def num():
def div2(num): return 10
def inner():
n=num() print(num())
return n+n
return inner
Anand Komiripalem
Generators
Anand Komiripalem
Generators
Generator is a function which is responsible to generate a sequence
of values.
Generators are used to improve performance
If we need to handle large amounts of date, we can go with
generators.
Ex:
l=[x*x for x in range(10000000000)]
print(l[0]) #Error
In the above example all the values created and stored in a list first
and then the value l[0] will be displayed, but the given range is very
large and leads to memory Error
Anand Komiripalem
Generators
Instead of creating and storing all the values in the initial stage itself,
we can create the values when ever there is need for the values.\
Ex:
g=(x*x for x in range(100000000000))
print(next(g)) #0
print(next(g)) #1
print(type(g))
for x in g:
print(i)
Generators
We cannot get a specific value from generators as generators doesn’t support
indexing.
We can write generator functions just like ordinary functions, but it uses yield
keyword to return values.
Ex:
def mygen():
yield 'A'
yield 'B'
yield 'C'
g=mygen()
print(type(g)) #<class 'generator'>
print(next(g)) #A
print(next(g)) #B
print(next(g)) #C
print(next(g)) #Error
Anand Komiripalem
Generators
Ex:2
def countdown(num):
print("Start Countdown") Output:
while(num>0):
Start Countdown
yield num
5
num=num-1 4
3
values=countdown(5) 2
for x in values: 1
print(x)
Anand Komiripalem
Generators
Ex 3: To generate first n numbers
Output:
def firstn(num):
n=1 Start Countdown
1
while n<=num:
2
yield n 3
n=n+1 4
5
values=firstn(5)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for x in values:
print(x)
l1 = list(values)
print(l1)
Anand Komiripalem
Generators
Ex 4: To generate Fibonacci Numbers..
Output:
def fib():
a,b=0,1 Start Countdown
1
while True:
2
yield a 3
a,b=b,a+b 4
for f in fib(): 5
if f>100:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
break
print(f)
Anand Komiripalem
Packages
Package is a grouping mechanism or encapsulation mechanism
It is a collection of modules into a single unit, like folder in a system
In order to consider a folder as a package it should contain __init__.py file
init
From python 3.3 version __init__.py file is optional to have in a folder
A package can have sub packages in it
Anand Komiripalem
Packages
Advantages of Python:
We can resolve naming conflicts
We can identify our components uniquely
Modularity will be improved
Readability will be improved and improvability will be easy
Importing Packages:
Import.package.module_name
Package.module_name.function
(Or)