In [ ]:
# function
# one single program - 1000 lines
# block of the code and call it when required.
#

In [1]:
def my_func():
    print "hello world"

In [8]:
def my_func1():
    return "hello world"
    print "hey today is monday"
    print "today we are going to have fun"

In [4]:
print type(my_func)
print my_func
my_func


<type 'function'>
<function my_func at 0x7fbd314dcc80>
Out[4]:
<function __main__.my_func>

In [5]:
# run the code
# you function has  return value.
# either you return or you get a none value.
# Marks the end of the function.
# can we use return more than once in a function. yes, with a conditional statements.
print my_func()


hello world
None

In [9]:
print my_func1()


hello world

In [10]:
# namespaces
# local or global variables

In [14]:
# variable defined inside a function are called local variables.
# They come into action during the run time of the function.
# Lifespan of the local variables is during the run time of the function.
# can i access the local variables outside the function ? NO

def my_new():
    x = 1
    print locals()
    return x

In [15]:
y = 10
def my_new():
    print locals()
    return y

print my_new()


{}
10

In [14]:
y = 10
def my_new():
    y = 20
    print locals()
    return y

print my_new()


{'y': 20}
20

In [15]:
print my_new()


{'x': 1}
1

In [13]:
print x


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-13-2d264e11d975> in <module>()
----> 1 print x

NameError: name 'x' is not defined

In [19]:
# Scope Resolution
# First look locally and then globally.
# locals -> give the namespace/variables available to us locally.
# globals -> give the namespace/variables available to us globally.

x = 10
def my_new():
    x = 2
    print locals()
    return x

print globals()


{'_dh': [u'/home/tcloudost/Documents/git_repositories/python-batches/batch-56'], '__': '', 'my_func': <function my_func at 0x7fbd314dcc80>, '__builtin__': <module '__builtin__' (built-in)>, '_iii': u'# Scope Resolution\n\nx = 10\ndef my_new():\n    print locals()\n    return x\n\nprint globals()', 'quit': <IPython.core.autocall.ZMQExitAutocall object at 0x7fbd32dad0d0>, '_i9': u'print my_func1()', '_i8': u'def my_func1():\n    return "hello world"\n    print "hey today is monday"\n    print "today we are going to have fun"', '_i7': u'print my_func1()', '_i6': u'def my_func1():\n    return "hello world"', '_i5': u'# run the code\nprint my_func()', '_i4': u'print type(my_func)\nprint my_func\nmy_func', '_i3': u'print type(my_func)\nprint my_func', '_i2': u'print type(my_func)', '_i1': u'def my_func():\n    print "hello world"', 'exit': <IPython.core.autocall.ZMQExitAutocall object at 0x7fbd32dad0d0>, 'get_ipython': <bound method ZMQInteractiveShell.get_ipython of <ipykernel.zmqshell.ZMQInteractiveShell object at 0x7fbd3b9934d0>>, '_i': u'print my_new()', '_i14': u'def my_new():\n    x = 1\n    print locals()\n    return x', '__doc__': 'Automatically created module for IPython interactive environment', 'my_new': <function my_new at 0x7fbd30c65ed8>, '_ii': u'print my_new()', '__builtins__': <module '__builtin__' (built-in)>, 'In': ['', u'def my_func():\n    print "hello world"', u'print type(my_func)', u'print type(my_func)\nprint my_func', u'print type(my_func)\nprint my_func\nmy_func', u'# run the code\nprint my_func()', u'def my_func1():\n    return "hello world"', u'print my_func1()', u'def my_func1():\n    return "hello world"\n    print "hey today is monday"\n    print "today we are going to have fun"', u'print my_func1()', u'# namespaces\n# local or global variables', u'def my_new():\n    x = 1\n    return x', u'print my_new()', u'print x', u'def my_new():\n    x = 1\n    print locals()\n    return x', u'print my_new()', u'# Scope Resolution\n\nx = 10\ndef my_new():\n    print locals()\n    return x\n\nprint globals()', u'print my_new()', u'print my_new()', u'# Scope Resolution\n# First look locally and then globally.\n\nx = 10\ndef my_new():\n    x = 2\n    print locals()\n    return x\n\nprint globals()'], 'my_func1': <function my_func1 at 0x7fbd314dcde8>, '__name__': '__main__', '___': '', '_': <function my_func at 0x7fbd314dcc80>, '_sh': <module 'IPython.core.shadowns' from '/usr/local/lib/python2.7/dist-packages/IPython/core/shadowns.pyc'>, '_4': <function my_func at 0x7fbd314dcc80>, '_i13': u'print x', '_i12': u'print my_new()', '_i11': u'def my_new():\n    x = 1\n    return x', '_i10': u'# namespaces\n# local or global variables', '_i17': u'print my_new()', '_i16': u'# Scope Resolution\n\nx = 10\ndef my_new():\n    print locals()\n    return x\n\nprint globals()', '_i15': u'print my_new()', '_ih': ['', u'def my_func():\n    print "hello world"', u'print type(my_func)', u'print type(my_func)\nprint my_func', u'print type(my_func)\nprint my_func\nmy_func', u'# run the code\nprint my_func()', u'def my_func1():\n    return "hello world"', u'print my_func1()', u'def my_func1():\n    return "hello world"\n    print "hey today is monday"\n    print "today we are going to have fun"', u'print my_func1()', u'# namespaces\n# local or global variables', u'def my_new():\n    x = 1\n    return x', u'print my_new()', u'print x', u'def my_new():\n    x = 1\n    print locals()\n    return x', u'print my_new()', u'# Scope Resolution\n\nx = 10\ndef my_new():\n    print locals()\n    return x\n\nprint globals()', u'print my_new()', u'print my_new()', u'# Scope Resolution\n# First look locally and then globally.\n\nx = 10\ndef my_new():\n    x = 2\n    print locals()\n    return x\n\nprint globals()'], 'x': 10, '_i19': u'# Scope Resolution\n# First look locally and then globally.\n\nx = 10\ndef my_new():\n    x = 2\n    print locals()\n    return x\n\nprint globals()', '_i18': u'print my_new()', '_oh': {4: <function my_func at 0x7fbd314dcc80>}, 'Out': {4: <function my_func at 0x7fbd314dcc80>}}

In [ ]:
# 'x': 10,
# 4th line from bottom.

In [17]:
print my_new()


{}
10

In [20]:
print my_new()


{'x': 2}
2

In [21]:
print x


10

In [8]:
# global

balance = 0

def deposit():
    global balance
    print locals()
    balance = balance + 1000
    return balance

def withdraw():
    global balance
    print locals()
    balance = balance - 300
    return balance

# Main
print deposit()
print balance
print deposit()
print withdraw()
print balance


{}
1000
1000
{}
2000
{}
1700
1700

In [9]:
# functional paremeters

def my_add(a,b):
    return a + b

In [10]:
# positional functional arguments

print my_add(10,20)
print my_add('linux','rocks')
print my_add('rocks','linux')


30
linuxrocks
rockslinux

In [11]:
# key based functional arguments

print my_add(b='rocks',a='linux')


linuxrocks

In [18]:
# default arguments

def multi(num,kumar=10):
    for value in range(1,kumar+1):
        print "{} * {} = {}".format(num,value,num*value)
        
multi(2)
multi(3,5)


2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
3 * 4 = 12
3 * 5 = 15

In [ ]:
# putty - http://cache.filehippo.com/img/ex/1125__putty1.png
# def putty(hostname,port=22)
# putty(hostname) # ssh
# putty(hostname,23) # telnet

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

In [21]:
# *
def my_add(a,b):
    return a + b

my_list = [10,20]
#(a,b) = my_list
# a = my_list[0]
# b = my_list[1]

print my_add(my_list)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-21-95abd6191a0c> in <module>()
      8 # b = my_list[1]
      9 
---> 10 print my_add(my_list)

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

In [22]:
print my_add(*my_list)


30

In [23]:
my_list2= [10,20,30]
print my_add(*my_list2)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-23-b08b83604235> in <module>()
      1 my_list2= [10,20,30]
----> 2 print my_add(*my_list2)

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

In [24]:
# **
def my_add(a,b):
    return a + b

my_dict = {'b':20,'a':10}
print my_add(**my_dict)


30

In [25]:
my_dict1 = {'b':30,'c':20}
print my_add(**my_dict1)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-25-f967606e8c5d> in <module>()
      1 my_dict1 = {'b':30,'c':20}
----> 2 print my_add(**my_dict1)

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

In [26]:
# *args

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 [28]:
print max(-5,-1)
print max(22,33,14,51,62,74,89,20)


-1
89

In [30]:
# 
def gmax(*args):
    big=-1
    for value in args:
        if value > big:
            big = value
    return big


print gmax(-5,-1)
print gmax(22,33,14,51,62,74,89,20)


-1
89

In [31]:
# **kwargs

def my_callme(**kwargs):
    print kwargs
    
my_callme(name='kumar',gender='m')
my_callme(name='kumar',mobile='x.u.y.z')
my_callme(location='hyd',mother='laxmi')


{'gender': 'm', 'name': 'kumar'}
{'mobile': 'x.u.y.z', 'name': 'kumar'}
{'location': 'hyd', 'mother': 'laxmi'}

In [1]:
def my_callme(**kwargs):
    if 'name' in kwargs:
        print "your name is {}".format(kwargs['name'])
    if 'gender' in kwargs:
        print "your gender is {}".format(kwargs['gender'])
    if 'mobile' in kwargs:
        print "your mobile is {}".format(kwargs['mobile'])
    if 'location' in kwargs:
        print "your location is {}".format(kwargs['location'])
    if 'mother' in kwargs:
        print "your mother name is {}".format(kwargs['mother'])

In [2]:
my_callme(name='kumar',gender='m')
my_callme(name='kumar',mobile='x.u.y.z')
my_callme(location='hyd',mother='laxmi')


your name is kumar
your gender is m
your name is kumar
your mobile is x.u.y.z
your location is hyd
your mother name is laxmi

In [6]:
# function witin a function

def outer():
    x = 1
    def inner():
        return x
    print locals()
    return inner()  # calling the the inner function

# Main
print outer() # 1
print inner()  # inner is local to outer function so is not available.


{'x': 1, 'inner': <function inner at 0x7fa9605abed8>}
1
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-6-922b5cbaad59> in <module>()
     10 # Main
     11 print outer() # 1
---> 12 print inner()  # inner is local to outer function so is not available.

NameError: name 'inner' is not defined

In [9]:
# Function Closures
# All the variables available toa function during defination time, are available even if we 
# return it as a address.


def outer():
    x = 1
    def inner():
        return x
    print locals()
    return inner  # you are returning the inner function address.

# Main
foo = outer()
print foo,type(foo)
print foo() # 1
print x
#print inner()  # inner is local to outer function so is not available.


{'x': 1, 'inner': <function inner at 0x7fa9605c00c8>}
<function inner at 0x7fa9605c00c8> <type 'function'>
1
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-9-a1524f55429c> in <module>()
     13 print foo,type(foo)
     14 print foo() # 1
---> 15 print x
     16 #print inner()  # inner is local to outer function so is not available.

NameError: name 'x' is not defined

In [10]:
# Functions are first class object.

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

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

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

print extra(add,2,4) # 6
print extra(sub,4,2) # 2


6
2

In [11]:
# map,filter and lambda

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 [12]:
# map

def square(a):
    return a * a

print square(2) # 4
print square(25) # 625


4
625

In [13]:
print map(square,[21,22,23,24,25])
         # function,arguement sequence


[441, 484, 529, 576, 625]

In [14]:
# 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 [16]:
def even(a):
    if a % 2 == 0:
        return 'even'

print even(2) # even # True
print even(3) # None # False


even
None

In [17]:
print filter(even,[21,22,23,24,25])


[22, 24]

In [21]:
# some fun
print map(square,range(1,11))
print filter(square,range(1,11))
print map(even,range(1,11))
print filter(even,range(1,11))


[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[None, 'even', None, 'even', None, 'even', None, 'even', None, 'even']
[2, 4, 6, 8, 10]

In [23]:
# lambda
# creation of a nameless function. creation of a function on fly.

print map(lambda a:a*a,range(1,11))
print filter(lambda a:a%2==0,range(1,11))


[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[2, 4, 6, 8, 10]

In [ ]: