DAY 6 - Function ,lambda ,module ,Iterator ,map ,filter ,reduce ,List Comprehension ,Exception Handling ,*args ,**kwargs

#Function #lambda #module #Iterator #map #filter #reduce #ListComprehension #ExceptionHandling #*args #**kwargs

1. Function :
   A function is a reusable block of programming statements designed to perform a certain task.
 
def function_name(parameters):
    statement-n
    return [expr]
   
for example,
def Myself(name, age, gender):
    if gender == 'M':
       print ("Hey Man.Who are you ? ")
       print ("Hi! My name is {} and I am {} years old".format(name,age))
    else:
       print ("Hey Ma'am.Who are you ? ")
       print ("Hi! My name is {} and I am {} years old".format(name,age))
    return

>>> Myself('Rakesh',30,'M')
o/p:
Hey Man.Who are you ?
Hi! My name is Rakesh and I am 30 years old

#Recursive Function : Recursive function involves successively calling it by decrementing the number until it reaches 1 to calculate factorial.
 Same logic is applicable for any other case.

for example,
def factorial(n):   
    if n == 1:
        print(n)
        return 1   
    else:
        print (n,'*', end=' ')
        return n * factorial(n-1)

or
from functools import reduce
fact_n = reduce(lambda x,y:x*y,range(1,n+1))

# How to use *args and **kwargs in Python
The special syntax, *args and **kwargs in function definitions is used to pass a variable number of arguments to a function.
The single asterisk form (*args) is used to pass a non-keyworded, variable-length argument list, and the double asterisk form is used to pass a keyworded,
variable-length argument list.

Note - input parameter for kwargs is a dictionary object 

Example 1:
def test_var_args(farg, *args):
    print "formal arg:", farg
    for arg in args:
        print "another arg:", arg

test_var_args(1, "two", 3)

o/p:
formal arg: 1
another arg: two
another arg: 3

Example 2:
def test_var_kwargs(farg, **kwargs):
    print "formal arg:", farg
    for key in kwargs:
        print "another keyword arg: %s: %s" % (key, kwargs[key])

test_var_kwargs(farg=1, myarg2="two", myarg3=3)

o/p:
formal arg: 1
another keyword arg: myarg2: two
another keyword arg: myarg3: 3

Example 3:
def myFun(arg1, *args):
    print ("First argument :", arg1)
    for arg in argv:
        print("Next argument through *argv :", arg)
 
myFun('Hello', 'Welcome', 'to', 'World')
o/p:
First argument : Hello
Next argument through *argv : Welcome
Next argument through *argv : to
Next argument through *argv : World

Example 4:
def myFun(**kwargs): 
    for key, value in kwargs.items():
        print ("%s == %s" %(key, value))
 
# Driver code
myFun(first ='The Sky', mid ='Is', last='Pink') 
o/p:
last == Pink
mid == Is
first == The Sky

Example 5:
def myFun(arg1, arg2, arg3):
    print("arg1:", arg1)
    print("arg2:", arg2)
    print("arg3:", arg3)
     
# Now we can use *args or **kwargs to
# pass arguments to this function : 
args = ("The Sky", "Is", "Pink")
myFun(*args)
 
kwargs = {"arg1" : "The Sky", "arg2" : "Is", "arg3" : "Pink"}
myFun(**kwargs)
o/p:
arg1: The Sky
arg2: Is
arg3: Pink
arg1: The Sky
arg2: Is
arg3: Pink


2. Lambda function - Temporary function/Run Time Function/one Time Function 
   lambda keyword is used to create anonymous functions. Usually, such a function is meant for one-     time use.
 
lambda arg1, arg2... : expression

for example:
>>> math_opr = lambda x, y, z : x ** y * z
>>> math_opr(2,3,4)
32

3. Module -
    Any text file with the .py extension containing Python code is basically a module.
    Different Python objects such as functions, classes, variables, constants, etc., defined in one module can be made available to an interpreter session or another Python script by using the import statement.

>>> import sys 
>>> sys.path
['C:\\Users\\Rakesh.Ranjan\\Desktop', 'C:\\Users\\Rakesh.Ranjan\\AppData\\Local\\Programs\\Python\\Python37-32\\Lib\\idlelib',
'C:\\Users\\Rakesh.Ranjan\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip', 'C:\\Users\\Rakesh.Ranjan\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs',
'C:\\Users\\Rakesh.Ranjan\\AppData\\Local\\Programs\\Python\\Python37-32\\lib', 'C:\\Users\\Rakesh.Ranjan\\AppData\\Local\\Programs\\Python\\Python37-32',
'C:\\Users\\Rakesh.Ranjan\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages']

If the required module is not present in any of the directories above, the message ModuleNotFoundError is thrown.So place working piece + calling modules in above paths.

for example,
>>> import Myself
Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    import Myself
ModuleNotFoundError: No module named 'Myself'

>>> test
<module 'test' from 'C:\\Users\\Rakesh.Ranjan\\Desktop\\test.py'>

>>> help('test')
Help on module test:

NAME
    test

FUNCTIONS
    Myself(name, age, gender)

FILE
    c:\users\rakesh.ranjan\desktop\test.py


>>> help('sys')

>>> help('modules')


>>> import test #no error

#Alg_Opr.py
def sum(x,y):
    return x+y
def average(x,y):
    return (x+y)/2
def power(x,y):
    return x**y

from functions import sum, average
print("sum: ", sum(10, 20)) # Output: sum: 30
print("average: ", average(10, 20)) # Output: average: 15


4. Iterator -
   Python's built-in method iter() receives an iterable and returns an iterator object.

for example,
>>> Sibling=['Rakesh','Rupesh','Ritesh']
>>> it=iter(Sibling)
>>>next(it)
'Rakesh'
>>>next(it)
'Rupesh'
>>>next(it)
'Ritesh'
>>>next(it)
Traceback (most recent call last):
  File "<pyshell#42>", line 1, in <module>
    next(it)
StopIteration

Note - If the argument is not iterable, e.g. number, boolean, etc., TypeError is encountered.
>>> iter(2)
Traceback (most recent call last):
  File "<pyshell#43>", line 1, in <module>
    iter(2)
TypeError: 'int' object is not iterable

Exception handling:
num_list = List[range(1,10)]
while True:
    try:
        print ("Received on next(): ",next(num_list))
    except StopIteration:
        break
       
5. map(function, iterable [, iterable2, iterable3,...iterableN]) --> map object
   where iterable can be string, list, tuple or dictionary and iterable count depends on input parameters of function


 
#Convert map object into list to to read its data or use next() function
for example,
>>> sqrList = map(lambda x: x*x, [1, 2, 3, 4])
>>> next(sqrList)
1

or
>>> sqrList = list(map(lambda x: x*x, [1, 2, 3, 4]))
>>> sqrList

>>> bases=[10, 20, 30, 40, 50]
>>> index=[1, 2, 3, 4, 5]
>>> powers=list(map(pow, bases, index))
>>> powers
[10, 400, 27000, 2560000, 312500000]

>>> first_name = ['Rakesh','Rupesh','Ritesh','Puja']
>>> last_name = ['Ranjan','Kumar','Kumar','Gupta']
>>> full_name = lambda x,y: [x[i] +' ' +  y[i] for i in range(0,len(x))]
>>> full_name(first_name,last_name)
['Rakesh Ranjan', 'Rupesh Kumar', 'Ritesh Kumar', 'Puja Gupta']

>> full_name = lambda x,y: [x[i] +' ' +  y[i] for i in range(0,len(first_name))]
>> list(map(full_name,first_name,last_name))
[['R R', 'a a', 'k n', 'e j'], ['R K', 'u u', 'p m', 'e a'], ['R K', 'i u', 't m', 'e a'], ['P G', 'u u', 'j p', 'a t']]

Note: Map function picks one element at a time from iterable object and does operation over these element(s) . This invisible loop goes on till last element.
      So there is no need to write a loop explicitly for iteration of iterable object inside map function.


6. filter(function, iterable) --> filter object
   The filter() function calls the specified function which returns boolen value i.e. True or False .Only those items which return True are stored in a filter object.
   The filterr object would be subset of list/tuple/dictionary

for example, 
>>> div_by_3_list = list(filter(lambda x:x%3 == 0,[3,4,5,6,7,8,9,10]))
>>> div_by_3_list
[3, 6, 9]

def isPrime(x):
    for n in range(2,x):
        if x%n==0:
            return False
        else:
            return True

fltrObj=filter(isPrime, range(10))
print ('Prime numbers between 1-10:', list(fltrObj))
o/p:
Prime numbers between 1-10: [3, 5, 7, 9]



fltrObj=filter(lambda x: x%2==0, range(10))
print(list(fltrObj))


7. reduce(function, iterable) --> reduce object (i.e which is either integer or string in 90% of case )
   The reduce() function receives two arguments, a function and an iterable. However, it doesn't return another iterable, instead it returns a single value.
 
   The argument function is applied cumulatively to arguments in the list from left to right. The result of the function in the first call becomes the first argument
   and the third item in list becomes second. This is repeated until the list is exhausted.
 
for example,

from functools import reduce
>>> sum_range = reduce(lambda x,y: x + y,range(1,4))
>>> sum_range # 1 + 2 then 3 + 3
6


Overview of functions # map(),filter() and reduce()
###################################################
1. map(function,seq) --> returns sequence of same length
2.filter(function_which_returns_boolean_value,seq) --> returns sub-set of original sequence
3.reduce(function,seq) --> returns single value


8. List Comprehension - 
   List comprehension is considerably faster than processing a list using the for loop.
   In List comprehension,first place the operation/output expression,followed by for-loop statement in sequenece from top to bottom.
 
for example,
>>> square_list = [x*x for x in range(1,10)]
#[1, 4, 9, 16, 25, 36, 49, 64, 81]


>>> paragraph = ["Rakesh is elder brother of his family.","He is least responsible member in his family","Whereas his younger siblings are more responsible"]
>>> single_word_list = [word for sentence in paragraph for word in sentence.split()]
#['Rakesh', 'is', 'elder', 'brother', 'of', 'his', 'family.', 'He', 'is', 'least', 'responsible', 'member', 'in', 'his', 'family', 'Whereas', 'his', 'younger', 'siblings', 'are', 'more', 'responsible']


>>>list1=[1,2,3]
>>>list2=[4,5,6]
>>>CombLst=[(x,y) for x in list1 for y in list2]
>>>CombLst
[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]


>>> [x for x in range(21) if x%2==0]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]


>>> [x for x in range(21) if x%2==0 if x%5==0]
[0, 10, 20]


>>> obj=[str(i)+" = Even" if i%2==0 else str(i)+" = Odd" for i in range(10)]
>>> obj
['0 = Even', '1 = Odd', '2 = Even', '3 = Odd', '4 = Even', '5 = Odd', '6 = Even', '7 = Odd', '8 = Even', '9 = Odd']

9. Exception Handling - 

try:
    #statements in try block
except:
    #executed when error in try block
else:
    #executed if try block is error-free
finally:
    #executed irrespective of exception occured or not
   
   
for example,
try:
    print("try block")
    x=int(input('Enter a number: '))
    y=int(input('Enter another number: '))
    z=x/y
   
except TypeError:
    print('Unsupported operation')
   
except ZeroDivisionError:
    print("except ZeroDivisionError block")
    print("Division by 0 not accepted")

except:
    print('Some error occurred.')
   
else:
    print("else block")
    print("Division = ", z)
finally:
    print("finally block")
    x=0
    y=0
print ("Out of try, except, else and finally blocks." )

#Execution
try block
Enter a number: 1
Enter another number: [1,2,3]
Some error occurred.
finally block
Out of try, except, else and finally blocks.


User-Defined Exception:
try:
    x=int(input('Enter a number upto 100: '))
    if x > 100:
        raise ValueError(x)
except ValueError:
    print(x, "is out of allowed range")
else:
    print(x, "is within the allowed range")

#RR #Day6 #Python #Function #lambda #module #Iterator #map #filter #reduce #ListComprehension #ExceptionHandling #*args #**kwargs #HappyLearning #WeLearnEveryday

Comments

Popular posts from this blog

Day 32 - Python Script to track Available COVID-19 Vaccine Slots for 18+ in India

DAY 1 - Steps to prepare your windows laptop for Python Programming

Day 26 - Call Power BI REST APIs to get POWER BI REPORT Details