In [ ]:
# *,**,*args,**kwargs

In [1]:
def my_func(a,b):
    return a + b
    
print my_func("linux","rocks")


linuxrocks

In [7]:
my_list = ["linux"," rocks"]
my_list1 = ["linux","rocks","fine"]
my_list2 = ["linux"]

# please unpack the elements "linux" and "rocks" into both a and b.
print my_func(*my_list)  # unpacking your list to a funtion.
print my_func(*my_list1)


linux rocks
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-d695b25770df> in <module>()
      5 # please unpack the elements "linux" and "rocks" into both a and b.
      6 print my_func(*my_list)
----> 7 print my_func(*my_list1)

TypeError: my_func() takes exactly 2 arguments (3 given)

In [8]:
print my_func(*my_list2)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-8-ffe05c32b4ea> in <module>()
----> 1 print my_func(*my_list2)

TypeError: my_func() takes exactly 2 arguments (1 given)

In [ ]:
# **

In [10]:
def my_func(a,b):
    return a + b

print my_func(a="linux",b=" rocks") # keyword arguments


linux rocks

In [12]:
# dictionary
my_values = {'a':"linux",'b':" rocks"}
print my_func(**my_values)


linuxrocks

In [13]:
my_values1 = {'a':"linux",'b':" rocks",'c':'choco'}
print my_func(**my_values1)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-13-4a61bc41e41c> in <module>()
      1 my_values1 = {'a':"linux",'b':" rocks",'c':'choco'}
----> 2 print my_func(**my_values1)

TypeError: my_func() got an unexpected keyword argument 'c'

In [1]:
# *args
# More than one argument.

print help(max)


Help on built-in function max in module __builtin__:

max(...)
    max(iterable[, key=func]) -> value
    max(a, b, c, ...[, key=func]) -> value
    
    With a single iterable argument, return its largest item.
    With two or more arguments, return the largest argument.

None

In [3]:
print max(23,24,25,61)
print max(1,61)


61
61

In [4]:
# gmax
# if a function defination has *args and if you return args, you get a tuple of values.
def gmax(*args):
    return args

In [5]:
print gmax(21,31,51,63,66)
print gmax(31,21)


(21, 31, 51, 63, 66)
(31, 21)

In [10]:
# *args basically passes n number of functions.
def gmax(*args):
    big = 0
    print args
    for value in args:
        print "following are the values : big {} , value {}".format(big,value)
        if value > big:
            big = value
    return big

In [11]:
print gmax(21,31,51,63,66)
print gmax(31,21)


(21, 31, 51, 63, 66)
following are the values : big 0 , value 21
following are the values : big 21 , value 31
following are the values : big 31 , value 51
following are the values : big 51 , value 63
following are the values : big 63 , value 66
66
(31, 21)
following are the values : big 0 , value 31
following are the values : big 31 , value 21
31

In [12]:
# **kwargs
def callme(**kwargs):
    return kwargs   # dictionary of values.

print callme(name="kumar",age="45")
print callme(name="kumar",maiden="vijaya")
print callme(gender='m',location="hyd")


{'age': '45', 'name': 'kumar'}
{'name': 'kumar', 'maiden': 'vijaya'}
{'gender': 'm', 'location': 'hyd'}

In [16]:
def callme(**kwargs):
    if 'name' in kwargs:
        print "my name is {}".format(kwargs['name'])
    if 'age' in kwargs:
        print "my age is {}".format(kwargs['age'])
    if 'maiden' in kwargs:
        print "my mother name is {}".format(kwargs['maiden'])
    if 'location' in kwargs:
        print "The location is {}".format(kwargs['location'])
    if 'gender' in kwargs:
        print "the gender is {}".format(kwargs['gender'])
        
        
# main

#callme(name="kumar",age="45")
#callme(name="kumar",maiden="vijaya")
callme(gender='m',location="hyd")


The location is hyd
the gender is m

In [20]:
# some defination of functions

def foo():
    pass

In [21]:
foo


Out[21]:
<function __main__.foo>

In [22]:
print type(foo)


<type 'function'>

In [23]:
print foo


<function foo at 0x7f3cf8b1bde8>

In [28]:
# function within a functions.
# the local variables are resticted to function.
# the lifetime of the local variables is during the runtime of the function.

def upper():
    x = 1              # local variable for upper() function.
    def inner():       # inner() function is a local variable/function within your upper() function.
        return x       # x is going to be fetched from global value x of upper() function.
    print locals()
    return inner()     # you are returing the value of inner() function

In [29]:
print upper() # 1


{'x': 1, 'inner': <function inner at 0x7f3cf8b1bd70>}
1

In [19]:
print inner() # Error


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-19-4d12a7e2137b> in <module>()
----> 1 print inner() # Error

NameError: name 'inner' is not defined

In [30]:
# function within a functions.
# the local variables are resticted to function.
# the lifetime of the local variables is during the runtime of the function.
# how did inner() function get the value x.
# function closures: During the defination of the function , all the global and the local variables available will be present
# even when we return the address of the function.

def upper():
    x = 1              # local variable for upper() function.
    def inner():       # inner() function is a local variable/function within your upper() function.
        return x       # x is going to be fetched from global value x of upper() function.
    print locals()
    return inner       # you are returing the address of the inner function.

In [31]:
new = upper()


{'x': 1, 'inner': <function inner at 0x7f3cf8b1bed8>}

In [32]:
print new


<function inner at 0x7f3cf8b1bed8>

In [27]:
print new()


1

In [33]:
# function is a first class object.
# int,float,str as first class objects.

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

def sub(x,y):
    return x - y

def extra(func,x,y):
    return func(x,y)

In [34]:
print extra(add,22,23)
print extra(sub,25,23)


45
2

In [ ]:
# map,filter and lambda

In [35]:
print help(map)


Help on built-in function map in module __builtin__:

map(...)
    map(function, sequence[, sequence, ...]) -> list
    
    Return a list of the results of applying the function to the items of
    the argument sequence(s).  If more than one sequence is given, the
    function is called with an argument list consisting of the corresponding
    item of each sequence, substituting None for missing values when not all
    sequences have the same length.  If the function is None, return a list of
    the items of the sequence (or a list of tuples if more than one sequence).

None

In [36]:
def my_square(a):
    return a * a

In [ ]:
# truth of function: if a function returns a value, its called the truth of a function.
# if a function return None its called as NOT A TRUE function.

In [37]:
print my_square(2)


4

In [38]:
print my_square(3)


9

In [40]:
print map(my_square,[22,25,27,29,33])


[484, 625, 729, 841, 1089]

In [46]:
print filter(my_square,[22,25,27,29,33])


[22, 25, 27, 29, 33]

In [44]:
# filter
print help(filter)


Help on built-in function filter in module __builtin__:

filter(...)
    filter(function or None, sequence) -> list, tuple, or string
    
    Return those items of sequence for which function(item) is true.  If
    function is None, return the items that are true.  If sequence is a tuple
    or string, return the same type, else return a list.

None

In [42]:
def my_even(a):
    if a % 2 == 0:
        return 'even'

In [43]:
print my_even(2)  # TRUTH OF A FUNCTIONS
print my_even(3)  # FALSE OF A FUNCTION.


even
None

In [45]:
print filter(my_even,[1,2,3,4,5])


[2, 4]

In [47]:
print map(my_even,[1,2,3,4,5])


[None, 'even', None, 'even', None]

In [51]:
# lambda : writing nameless functions on fly.

print map(my_square,[22,25,27,29,33])
print map(lambda a:a*a,[22,25,27,29,33])

print filter(my_even,[1,2,3,4,5])
print filter(lambda a:a % 2 == 0,[1,2,3,4,5])


[484, 625, 729, 841, 1089]
[484, 625, 729, 841, 1089]
[2, 4]
[2, 4]

In [ ]:
# https://github.com/zhiwehu/Python-programming-exercises/blob/master/100%2B%20Python%20challenging%20programming%20exercises.txt