You are on page 1of 78

Anand Komiripalem

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")

wish() Hello Good Morning

 We can pass parameters (values) in functions


 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.
def wish(name):
print("Hello",name," Good Morning")

wish(“Anand")  Hello Anand Good Morning


wish(“Sam") Hello Sam Good Morning
Anand Komiripalem

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

Function can take input values as parameters and executes business


logic, and returns output to the caller with return statement.
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) 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")

even_odd(10) #10 is Even Number


even_odd(15) #15 is Odd Number
Anand Komiripalem

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")

 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 syntaxerror.
Anand Komiripalem

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

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
Anand Komiripalem

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)

sum() #The Sum =0


sum(10) # The Sum =10
sum(10,20) #The Sum =30
sum(10,20,30,40) #The Sum =100
Anand Komiripalem

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

def f1(*s, n1):


result=0
for x in s:
result=result+x
print(n1,”:”result)

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() TypeError: f() missing 2 positional arguments: 'arg1' and 'arg2'

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

Functions: Types of Variables


Local Variables:
 The variables which are declared inside a function and are
accessible in that particular function only, such variables are called
as local variables
def f1():
a=10 # local variable
print(a)

def f2():
print(a)

f1() #10
f2() #error
Anand Komiripalem

Functions: Types of Variables


a=20
def f1():
a=10 # local variable
print(a)

def f2():
print(a)

f1() #10
f2() #20
Anand Komiripalem

Functions: Types of Variables


Global Keyword: To declare global variable inside function

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

def f2():
print(a)

f1() #777
f2() #777
Anand Komiripalem

Functions: Types of Variables


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

a = 10 # Global Variable
def f1():
a=777 #Local Variable
print(a)
print(globals()['a'])

f1() #10
#777
Anand Komiripalem

Functions: Recursive Functions


 A function that calls itself is known as Recursive Function.
 Used for reducing the length of the code and improves readability
 Complex problems can be solved easily
def factorial(n):
if n==0:
result=1
else:
result=n*factorial(n-1)
return result

print("Factorial of 4 is :",factorial(4)) #24


print("Factorial of 5 is :",factorial(5)) #120
Anand Komiripalem

Functions: Recursive Functions


Sum of n numbers:

def sumofn(n):
if n==1:
return 1
else:
return n + sumofn(n-1)

sumofn(16) #136
Anand Komiripalem

Functions: Recursive Functions


 Febinocci Series:
Output:

def f(n): febinocci number: 5


if n<=1: Fibonacci sequence:
0
return n
1
else: 1
return(f(n-1)+f(n-2)) 2
3
nterms = int(input("febinocci number: "))
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(f(i))
Anand Komiripalem

Functions: Anonymous Functions


 we can declare a function without any name, such type of nameless
functions are called anonymous functions or lambda functions.
 main purpose of anonymous function is just for instant use
Syntax : lambda argument : expression
Using normal Function:
Using lambda:
def sqrt(n):
s=lambda n:n*n
return n:n*n
print(s(4))
sqrt(4)
Output:
Output:
16
16
Anand Komiripalem

Functions: Anonymous Functions


 Lambda Function to find Sum of 2 given Numbers
s=lambda a,b:a+b
print("Sum is:",s(10,20)) #Sum is: 30
Print(“Sum is:",s(100,200)) #Sum is: 300

 Lambda Function to find biggest of given Values


s=lambda a,b:a if a>b else b
print("Biggest is:",s(10,20)) # Biggest is: 20
print(“Biggest is:",s(100,200)) # Biggest is: 200
Anand Komiripalem

Functions: Anonymous Functions


 we can pass function as argument to another function
 Lambda functions can be used along with built-in functions like
filter(), map() and reduce().
filter():
 The filter() takes in a function and a list as arguments.
Syntax: filter(function, sequence)
Using normal Function: Using lambda Function:

def isEven(x): l=[0,5,10,15,20,25,30]


if x%2==0: l1=list(filter(lambda x:x%2==0,l))
return True print(l1) #[0,10,20,30]
else:
return False l2=list(filter(lambda x:x%2!=0,l))
l=[0,5,10,15,20,25,30] print(l2) #[5,15,25]
l1=list(filter(isEven, l))
print(l1) #[0,10,20,30]
Anand Komiripalem

Functions: Anonymous Functions


Ex:
inp_list = ['t', ‘u', 't', 'o', 'r', 'i', 'a', 'l']
result = list(filter(lambda x: x!='t' , inp_list))
print(result) #['u', 'o', 'r', 'i', 'a', 'l']

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

Functions: Anonymous Functions


Map():
The map() function applies a given function to each item of an iterable
(list, tuple etc.) and returns a list of the results.
Syntax: map(function, sequence)

Using normal Function: Using lambda Function:

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

Functions: Anonymous Functions


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]

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

Functions: Anonymous Functions


reduce(): reduce() function reduces sequence of elements into a single
element by applying the specified function.
Syntax: reduce(function, sequence)
 reduce() is present in functools module and hence we should write
import statement.
from functools import *
l=[10,20,30,40,50]
result=reduce(lambda x,y:x+y,l)
print(result) # 150
result=reduce(lambda x,y:x*y,l)
print(result) #12000000

from functools import *


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

Functions: Function Aliasing


Function Aliasing:
For the existing function we can give another name, which is nothing
but function aliasing.
def wish(name):
print("Good Morning:",name)
Output:
greeting=wish
46888256
print(id(wish))
46888256
print(id(greeting))
Good Morning: Anand
greeting(‘Anand') Good Morning: Anand
wish(‘Anand')

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

Functions: Nested Function


 A function declared inside another function is nothing but nested
functions or inner functions.
def outer():
print("outer function started")
def inner():
print("inner function execution")
print("outer function calling inner function")
inner()
outer() Output:
Inner()  Error
outer function started
outer function calling inner function
inner function execution
error
Anand Komiripalem

Functions: Nested Function


 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.
 In order to call a inner function in the outer function then it should be in
return part and then assign it some variable.
def outer():
print("outer function started")
def inner():
print("inner function execution")
print("outer function returning inner function")
return inner Output:
f1=outer() outer function started
f1() outer function returning inner function
f1()
f1() inner function execution  for f1()
inner function execution  for f1()
inner function execution  for f1()
Anand Komiripalem

Functions: Nested Function


What is the difference between the following lines?
f1 = outer and f1 = outer()
 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

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.

mymath.py #file name


---------------
x = 200
Y=100
def add(a,b):
print("The Sum:",a+b)

def product(a,b):
print("The Product:",a*b)

 The above module contains 2 variables and 2 functions


Anand Komiripalem

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

From mymath import x,add


print(x) #200
add(10,20) #30
product(10,20) #error
Anand Komiripalem

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:

from mymath import x as a, add as sum


print(a) #200
sum(10,30) #40
Anand Komiripalem

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

Ex: ['__annotations__', '__builtins__', '__cached__', '__doc__',


'__file__', '__loader__', '__name__', '__package__', '__spec__' ]
Anand Komiripalem

Modules
The Special Variable __name__:

 This variable stores information regarding whether the program is


executed as an individual program or as a module.
 If the program executed as an individual program then the value of
this variable is __main__
 If the program executed as a module from some other program then
the value of this variable is the name of module where it is defined
 by using this __name__ variable we can identify whether the
program is executed directly or as a module.
Anand Komiripalem

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

To get the modules available in python


help(‘modules’)
Anand Komiripalem

Modules: Random Module


 Defines several functions to generate some random values
random(): generates some float value between 0 and 1 excluding the
limits
Output:
0.15720624845042397
from random import * ---------------------------------
0.95433406321847
print(random())
0.4920568917131689
print(“----------------”) 0.8732940887640129
for i in range(5): 0.7622388235272658
0.6587231098939921
print(random())
0.8573415658967232

randint(x,y): generates some int value between the given numbers


including the limits
Anand Komiripalem

Modules: Random Module


from random import * Output:
38
print(randint()) ----
print(“----------------”) 115
180
for i in range(5): 106
print(randint()) 185
167

uniform(): generates some random value between the given limits


excluding the limits
Output:
from random import * 68.63837829312799
print(uniform(1,100)) ---------------------------
161.59909023545111
print("----------------") 120.83689828251825
for i in range(5): 157.53375898087828
172.6639237811024
print(uniform(100,200)) 146.58774382153112
Anand Komiripalem

Modules: Random Module


randrange(start, end, step): generates random value in the given range

from random import *


print(randrange(10)) #6
print(randrange(1,100)) #57
print(randrange(1,100,5)) #91

choice(): returns a random object from a given list /tuple

from random import *


l=[10,20,30,50,60,70]
print(choice(l)) #30
print("---------------")
print(choice(l)) #70
print("---------------")
print(choice(l)) #20
Anand Komiripalem

Modules: Random Module


Sample(sequence, no_of_samples): generates sample multiple data from
a list or from any sequence

from random import *


l=[10,20,30,50,60,70]
print(sample(l,3)) #[60,20,30]

choices(sequence, k=number): gives same result as sample

from random import *


l=[10,20,30,50,60,70]
print(choices(l,k=3)) #[50, 30, 10]

l="hai how are you"


print(choices(l,k=3)) #['h', 'h', 'a']
Anand Komiripalem

Modules: Random Module


shuffle(): shuffles the elements in the given list

from random import *


l=[2,3,4,5,6,7,8,9,10]
shuffle(l)
print(l) #[8, 7, 2, 10, 3, 6, 4, 9, 5]

triangular(): works like randrange() function but it gives floating point


values

from random import *


l=[2,3,4,5,6,7,8,9,10]
print(triangular(10,20)) #15.052009710993415
Anand Komiripalem

Modules: Random Module


Generating an OTP:

from random import *


print(randint(0,9), randint(0,9), randint(0,9), randint(0,9), randint(0,9),
randint(0,9),sep=“”)
print(“-----------------------------------------”)
for i in range(5):
print(randint(0,9), randint(0,9), randint(0,9), randint(0,9),
randint(0,9), randint(0,9),sep=“”) Output:
377972
----------
(Or) 433550
print(randint(100000,999999)) 827097
335368
063811
824449
Anand Komiripalem

Modules: Random Module


Generating an OTP with numbers and alphabets:

from random import *


print(chr(randint(65,90)), randint(0,9), chr(randint(65,90)), randint(0,9),
chr(randint(65,90)), randint(0,9),sep="")
print("-----------------------------------------")
for i in range(5):
print(chr(randint(65,90)), randint(0,9), chr(randint(65,90)), randint(0,9),
chr(randint(65,90)), randint(0,9),sep="")
Output:
L8C7X4
-----------------------------------------
D0X5Q6
R8Z8Q6
M0B7P0
R5D6Z6
F1U1R6
Anand Komiripalem

Modules: Random Module


Generate a random string of fixed length

import random
import string
def randomString(strlength=10):
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(strlength))

print ("Random String is ", randomString())


print ("Random String is ", randomString(10)) Output:
print ("Random String is ", randomString(10))
Random String is llkwrtwxys
Random String is rheglpppud
Random String is ramjqftxdq
Anand Komiripalem

Modules: Random Module


Generate a random string with alpha numeric characters

import random
import string
def randomStringDigits(strlen=2):
lettersAndDigits = string.ascii_letters + string.digits
return ''.join(random.choice(lettersAndDigits) for i in range(strlen))

print("First Random String is ", randomStringDigits(8))


print("Second Random String is ", randomStringDigits(8))
print("Third Random String is ", randomStringDigits(8))

Output:
First Random String is bQZv8vhi
Second Random String is A8zo6Qdr
Third Random String is oqobjDO1
Anand Komiripalem

Modules: Random Module


Generate a random string with alpha numeric and special Characters

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))

print ("First Random String ", randomS() )


print ("Second Random String", randomS(10) )
print ("Third Random String", randomS(10) )

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

 The main objective of decorator functions is that we can extend the


functionality of existing functions without modifying the original
function.
def wish(name):
print("Hello", name, "Good Morning")

wish("anand") #Hello anand Good Morning


wish("Ravi") #Hello Ravi Good Morning
wish("hari") #Hello hari you are worst fellow
Anand Komiripalem

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.

def decor(func): @decor


def inner(name): def wish(name):
if name=="hari": print("Hello", name, “GM")
print("Hello hari u r worst )
else: wish("anand") #Hello anand GM
func(name) wish("Ravi") #Hello Ravi GM
return inner wish("hari“) #Hello hari u r worst
Anand Komiripalem

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

def decorator(wish): @decorator


def inner(name): def wish(name):
if name=="hari": print("Hello", name, “GM")
print("Hello hari u r worst")
else: wish("anand") #Hello anand GM
wish(name) wish("Ravi") #Hello Ravi GM
return inner wish("hari“) #Hello hari u r worst
Anand Komiripalem

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)

 next(g) will print the next value in the sequence.


Anand Komiripalem

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)

from package.module_name import function()


function()

You might also like