In [ ]:
# Function
# Its a block of code.

In [6]:
# function
def my_fun():
    print "hello world"
    
def my_func():
    return "hello world"
    print "how are you"
    print "what are you doing"

In [3]:
# Every function has a return value.
# if your function has no return value it gives None.
print my_fun()


hello world
None

In [7]:
# If you have a return value in a function, that is the last statement to be executed in function.
# return is not a print statement.
# it marks end of the function.
print my_func()


hello world

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


<type 'function'>
<function my_func at 0x7fa78c28ae60>
Out[10]:
<function __main__.my_func>

In [12]:
# scope
# local scope/namespace and global scope/namespace.
# values defined inside a function are restricted to the function.
# life space of a variable is during the runtime of the function.
# locals() : is a inbuild function to see only local namespaces
# 

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

print my_new() # 1
print a  # 1,error


{'a': 1}
1
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-12-a3823ea901f1> in <module>()
     11 
     12 print my_new() # 1
---> 13 print a  # 1,error

NameError: name 'a' is not defined

In [14]:
# globals() : its a inbuild function which shows you all the variables, which are availabel to us.

x = 10 # global variable
print globals()


def my_new1():
    print locals()
    return x

print my_new1() # 10
# we got a value 10 for the function call as x is avaible globally.
# the first priority is given to local scope and then global scope.
print x


{'_dh': [u'/home/tcloudost/Documents/git_repositories/python-batches/batch-58'], '__': '', 'my_new': <function my_new at 0x7fa7928a8140>, '_i': u'x = 10\ndef my_new1():\n    print locals()\n    return x\n\nprint my_new1()\nprint x', 'quit': <IPython.core.autocall.ZMQExitAutocall object at 0x7fa78c3e1290>, '__builtins__': <module '__builtin__' (built-in)>, '_ih': ['', u'# function\ndef my_fun():\n    print "hello world"', u'my_fun2()', u'print my_fun()', u'# function\ndef my_fun():\n    print "hello world"\n    \ndef my_func():\n    return "hello world"', u'print my_func()', u'# function\ndef my_fun():\n    print "hello world"\n    \ndef my_func():\n    return "hello world"\n    print "how are you"\n    print "what are you doing"', u'# If you have a return value in a function, that is the last statement to be executed in function.\n# return is not a print statement.\n# it marks end of the function.\nprint my_func()', u'print type(my_func)', u'print type(my_func)\nprint my_func', u'print type(my_func)\nprint my_func\nmy_func', u'# scope\n# localscope and global scope.\n\ndef my_new():\n    a = 1\n    return a\n\nprint my_new() # 1\nprint a  # 1,error', u'# scope\n# local scope/namespace and global scope/namespace.\n# values defined inside a function are restricted to the function.\n# life space of a variable is during the runtime of the function.\n# locals\n\ndef my_new():\n    a = 1\n    print locals()\n    return a\n\nprint my_new() # 1\nprint a  # 1,error', u'x = 10\ndef my_new1():\n    print locals()\n    return x\n\nprint my_new1()\nprint x', u'x = 10 # global variable\nprint globals()\n\n\ndef my_new1():\n    print locals()\n    return x\n\nprint my_new1()\nprint x'], '__builtin__': <module '__builtin__' (built-in)>, '_10': <function my_func at 0x7fa78c28ae60>, 'my_new1': <function my_new1 at 0x7fa78c28acf8>, '__name__': '__main__', '___': '', '_': <function my_func at 0x7fa78c28ae60>, '_sh': <module 'IPython.core.shadowns' from '/usr/local/lib/python2.7/dist-packages/IPython/core/shadowns.pyc'>, 'my_fun': <function my_fun at 0x7fa78c2f2f50>, '_i11': u'# scope\n# localscope and global scope.\n\ndef my_new():\n    a = 1\n    return a\n\nprint my_new() # 1\nprint a  # 1,error', '_i9': u'print type(my_func)\nprint my_func', '_i8': u'print type(my_func)', '_i7': u'# If you have a return value in a function, that is the last statement to be executed in function.\n# return is not a print statement.\n# it marks end of the function.\nprint my_func()', '_i6': u'# function\ndef my_fun():\n    print "hello world"\n    \ndef my_func():\n    return "hello world"\n    print "how are you"\n    print "what are you doing"', '_i5': u'print my_func()', '_i4': u'# function\ndef my_fun():\n    print "hello world"\n    \ndef my_func():\n    return "hello world"', '_i3': u'print my_fun()', '_i2': u'my_fun2()', '_i1': u'# function\ndef my_fun():\n    print "hello world"', '__doc__': 'Automatically created module for IPython interactive environment', '_i13': u'x = 10\ndef my_new1():\n    print locals()\n    return x\n\nprint my_new1()\nprint x', 'my_func': <function my_func at 0x7fa78c28ae60>, '_iii': u'# scope\n# localscope and global scope.\n\ndef my_new():\n    a = 1\n    return a\n\nprint my_new() # 1\nprint a  # 1,error', '_i10': u'print type(my_func)\nprint my_func\nmy_func', 'exit': <IPython.core.autocall.ZMQExitAutocall object at 0x7fa78c3e1290>, 'get_ipython': <bound method ZMQInteractiveShell.get_ipython of <ipykernel.zmqshell.ZMQInteractiveShell object at 0x7fa795044950>>, '_ii': u'# scope\n# local scope/namespace and global scope/namespace.\n# values defined inside a function are restricted to the function.\n# life space of a variable is during the runtime of the function.\n# locals\n\ndef my_new():\n    a = 1\n    print locals()\n    return a\n\nprint my_new() # 1\nprint a  # 1,error', 'In': ['', u'# function\ndef my_fun():\n    print "hello world"', u'my_fun2()', u'print my_fun()', u'# function\ndef my_fun():\n    print "hello world"\n    \ndef my_func():\n    return "hello world"', u'print my_func()', u'# function\ndef my_fun():\n    print "hello world"\n    \ndef my_func():\n    return "hello world"\n    print "how are you"\n    print "what are you doing"', u'# If you have a return value in a function, that is the last statement to be executed in function.\n# return is not a print statement.\n# it marks end of the function.\nprint my_func()', u'print type(my_func)', u'print type(my_func)\nprint my_func', u'print type(my_func)\nprint my_func\nmy_func', u'# scope\n# localscope and global scope.\n\ndef my_new():\n    a = 1\n    return a\n\nprint my_new() # 1\nprint a  # 1,error', u'# scope\n# local scope/namespace and global scope/namespace.\n# values defined inside a function are restricted to the function.\n# life space of a variable is during the runtime of the function.\n# locals\n\ndef my_new():\n    a = 1\n    print locals()\n    return a\n\nprint my_new() # 1\nprint a  # 1,error', u'x = 10\ndef my_new1():\n    print locals()\n    return x\n\nprint my_new1()\nprint x', u'x = 10 # global variable\nprint globals()\n\n\ndef my_new1():\n    print locals()\n    return x\n\nprint my_new1()\nprint x'], '_i12': u'# scope\n# local scope/namespace and global scope/namespace.\n# values defined inside a function are restricted to the function.\n# life space of a variable is during the runtime of the function.\n# locals\n\ndef my_new():\n    a = 1\n    print locals()\n    return a\n\nprint my_new() # 1\nprint a  # 1,error', 'x': 10, '_i14': u'x = 10 # global variable\nprint globals()\n\n\ndef my_new1():\n    print locals()\n    return x\n\nprint my_new1()\nprint x', '_oh': {10: <function my_func at 0x7fa78c28ae60>}, 'Out': {10: <function my_func at 0x7fa78c28ae60>}}
{}
10
10

In [15]:
x = 10

def my_new1():
    x = 2
    print locals()
    return x

print my_new1() # 2
print x # 10


{'x': 2}
2
10

In [41]:
# global

balance=0

def my_deposit():
    global balance
    balance = balance + 1000
    return balance

def my_withdraw():
    global balance
    balance = balance - 300
    return balance

In [42]:
# calling dad
print my_deposit()


1000

In [43]:
print my_withdraw()


700

In [44]:
# Passing arguments
# in python arguments are passed as objects. not as references or values.
# passing functional arguments - positions
def my_func(a,b):
    print locals()
    return a + b

print my_func(2,3)


{'a': 2, 'b': 3}
5

In [36]:
# keys based - functional arguments
# 
def my_func(c,d):
    print locals()
    return c + d

print my_func(3,5)
print my_func(d=2,c=3)


{'c': 3, 'd': 5}
8
{'c': 3, 'd': 2}
5

In [5]:
# default: its not a key word.
# i am working on default argument

def my_multi(num,default=10):
    for value in range(1,default+1):
        print "{} * {} = {}".format(num,value,num*value)

my_multi(2)
my_multi(5,default=5)
my_multi(2,3)


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
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6

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

# putty(www.google.com)
# putty(www.google.com,port=23)

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

In [10]:
# *
my_list = [22,33]
my_list1 = [22,33,44]

def my_func(a,b):
    print locals()
    return a + b

# a = my_list[0]
# b = my_list[1]
# print my_func(a,b)
print my_func(my_list)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-95963bc77acf> in <module>()
     10 # b = my_list[1]
     11 # print my_func(a,b)
---> 12 print my_func(my_list)

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

In [8]:
print my_func(*my_list)


{'a': 22, 'b': 33}
55

In [11]:
print my_func(*my_list1)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-57ace6a63d1a> in <module>()
----> 1 print my_func(*my_list1)

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

In [13]:
# **
my_dict={'a':11,'b':12}
my_dict1 = {'a':12,'c':33}
print my_func(**my_dict)
print my_func(**my_dict1)


{'a': 11, 'b': 12}
23
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-13-599b542f421e> in <module>()
      3 my_dict1 = {'a':12,'c':33}
      4 print my_func(**my_dict)
----> 5 print my_func(**my_dict1)

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

In [14]:
# *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 [16]:
print max(22,33,44,95) 
print max(-1,-4)


95
-1

In [23]:
# gmax
def gmax(*args):
    return args

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

In [21]:
print gmax(22,33,44,95) 
print gmax(-1,-4)


95
-1

In [26]:
# **kwargs

def my_func(**kwargs):
    return kwargs

In [27]:
print my_func(name='kumar',gender='male')
print my_func(name='kumar',loc='hyd')
print my_func(maiden='vijaya',loc='hyd',name='kumar')


{'gender': 'male', 'name': 'kumar'}
{'loc': 'hyd', 'name': 'kumar'}
{'loc': 'hyd', 'name': 'kumar', 'maiden': 'vijaya'}

In [28]:
def my_func(**kwargs):
    if 'name' in kwargs:
        print "my name is {}".format(kwargs['name'])
    if 'gender' in kwargs:
        print "my gender is {}".format(kwargs['gender'])
    if 'loc' in kwargs:
        print "my location is {}".format(kwargs['loc'])
    if 'maiden' in kwargs:
        print "my mother name is {}".format(kwargs['maiden'])

In [29]:
print my_func(name='kumar',gender='male')
print my_func(name='kumar',loc='hyd')
print my_func(maiden='vijaya',loc='hyd',name='kumar')


my name is kumar
my gender is male
None
my name is kumar
my location is hyd
None
my name is kumar
my location is hyd
my mother name is vijaya
None

In [48]:
# function within a function

def upper():
    x = 1
    def lower():
        return x
    print lower()
    
print upper()  # 1,1,error
print lower()  # 1,error,error


1
None
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-48-3f8659ad5569> in <module>()
      8 
      9 print upper()  # 1,1,error
---> 10 print lower()  # 1,error,error

NameError: name 'lower' is not defined

In [4]:
# decorators
# variable available during the defination of a function,exits even when we return them.
# @ - decorator

def upper():
    x = 1
    def lower():
        return x
    return lower

foo = upper()  # the lower function is returned to value foo.
# after running upper function i neither see lower or x available for me.
# they are gone during the runtime of the function.

#print lower()
#print x

In [5]:
print foo
'''
    def lower():
        return x
'''
print foo()


<function lower at 0x7fa86ca1bf50>
1

In [6]:
# function are 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)

print extra(add,10,20) # 30
print extra(sub,30,10) # 20


30
20

In [ ]:
# map,filter and lambda

In [7]:
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 [9]:
def my_square(a):
    return a * a

print my_square(2)
print my_square(13)


4
169

In [14]:
print map(my_square,[11,12,13,14,15,16,17,18])
print filter(my_square,[11,12,13,14,15,16,17,18])


[121, 144, 169, 196, 225, 256, 289, 324]
[11, 12, 13, 14, 15, 16, 17, 18]

In [15]:
# 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 [12]:
def even(a):
    if a % 2 == 0:
        return 'even'
    
print even(2) # True
print even(3) # False


even
None

In [16]:
print filter(even,[1,2,3,4,5,6,7,8,9,10])
print map(even,[1,2,3,4,5,6,7,8,9,10])


[2, 4, 6, 8, 10]
[None, 'even', None, 'even', None, 'even', None, 'even', None, 'even']

In [18]:
# lambda
# creating nameless functions on fly.
print map(my_square,[11,12,13,14,15,16,17,18])
print map(lambda a:a*a,[11,12,13,14,15,16,17,18])


[121, 144, 169, 196, 225, 256, 289, 324]
[121, 144, 169, 196, 225, 256, 289, 324]

In [20]:
print filter(even,[1,2,3,4,5,6,7,8,9,10])
print filter(lambda a:a%2 ==0,[1,2,3,4,5,6,7,8,9,10])


[2, 4, 6, 8, 10]
[2, 4, 6, 8, 10]

In [ ]:


In [ ]: