In [ ]:
# Function
# A block of code,which can be called repetatively.
In [1]:
# defining a function
def my_func():
print "hey there!!"
In [2]:
print my_func # address of the function
print my_func() # calling the function.
my_func # my_func is part of our __main__ program. similar to void main in c++.
Out[2]:
In [ ]:
# every function has a return value.
# if a function has no retrun value we get None.
# return marks the end of the function.
In [5]:
def my_func():
return "hey there!!"
print "line1"
print "line2"
print "line3"
In [6]:
print my_func()
In [ ]:
# function scope/namespaces/variables
In [ ]:
# variable defined inside a function are restricted to the function.
# variable inside function/local scope variables get activated during run time of function.
# Lifespan of a variable is during the runtime of the function.
In [7]:
# case 1
def my_func():
a = 1
return a
In [ ]:
print my_func() # 1
In [8]:
print a
In [12]:
# case 2
# locals - show the local variables
a = 10 # global variable
def my_func():
print locals()
return a
In [13]:
print my_func() # 10
print a # 10
In [14]:
# case 3
# locals - show the local variables
# local variabels are given higher precedence than global variable.
a = 10 # global variable
def my_func():
a = 2
print locals()
return a
In [15]:
print my_func() # 2
print a # 10
In [16]:
# globals
print globals()
In [26]:
# global: keyword
balance = 0
def deposit():
global balance
print locals()
balance = balance + 1000
return balance
def withdraw():
global balance
print locals()
balance = balance - 300
return balance
In [18]:
# i see this error when the code was
'''
def deposit():
balance = balance + 1000
return balance
'''
print deposit()
In [27]:
print deposit()
In [28]:
print withdraw()
In [29]:
print balance
In [ ]:
# passing arguments,key arguments,default arguments
# *,**,*args,**kwargs
In [4]:
# passing arguments
# position based.
def my_add(a,b):
return a + b
print my_add(22,23)
print my_add('linux',' rocks')
print my_add(' rocks','linux')
In [6]:
# key based
def my_add(a,b):
return a + b
print my_add(b=22,a=23)
print my_add(a='linux',b=' rocks')
print my_add(b=' rocks',a='linux')
In [7]:
# default keys
# default is a variable not key word.
def my_multi(num,default=10):
for value in range(1,default+1):
print "{} * {} = {}".format(num,value,num*value)
In [8]:
print my_multi(2)
In [9]:
print my_multi(3,5)
In [10]:
print my_multi(default=5,num=10)
In [11]:
# http://cache.filehippo.com/img/ex/1125__putty1.png
def putty(hostname,port=22):
print "{},{}".format(hostname,port)
putty('www.google.com')
putty('www.amazon.com')
putty('www.icicibank.com',port=80)
putty('www.yahoo.com',port=23)
In [15]:
# *
def my_add(a,b):
return a + b
my_list = [22,23]
my_list1 = ['linux','rocks']
my_list2 = ['my','linux','rocks']
In [13]:
print my_add(my_list)
In [16]:
# * is unpacking the list to elements of a function.
print my_add(*my_list)
print my_add(*my_list1)
print my_add(*my_list2)
In [19]:
# **
my_dict = {'a':11,'b':22}
my_dict1 = {'a':'linux','b':'rocks'}
my_dict2 = {'a':'linux','c':'rocks'}
print my_add(**my_dict)
print my_add(**my_dict1)
print my_add(**my_dict2)
In [20]:
# *args
print help(max)
In [22]:
print max(77,21,31,48,99)
print max(-1,-2,-44,-55)
print max(2,4)
In [23]:
# gmax
# args a tuple of values passed to *args.
def gmax(*args):
print args
In [26]:
def gmax(*args):
big=-1
for value in args:
if value > big:
big = value
return big
In [27]:
print gmax(77,21,31,48,99)
print gmax(-1,-2,-44,-55)
print gmax(2,4)
In [28]:
# **kwargs
# kwargs returns a dictionary.
def callme(**kwargs):
return kwargs
In [29]:
print callme(name='kumar',gender='m')
print callme(name='kumar',maiden='vijaya')
print callme(name='kumar',maiden='vijaya',loc='hyd',gender='m')
In [32]:
def callme(**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 [33]:
print callme(name='kumar',gender='m')
print callme(name='kumar',maiden='vijaya')
print callme(name='kumar',maiden='vijaya',loc='hyd',gender='m')
In [35]:
# function is a first class object.
# function is just like any other object like string,number and integer.
def my_add(a,b):
return a + b
def my_sub(c,d):
return c - d
def my_extra(func,x,y):
return func(x,y)
In [36]:
print my_extra(my_add,22,33)
print my_extra(my_sub,33,22)
In [ ]:
# function within a function.
# function closures
# map,filter and lambda
In [ ]:
# function within a function
In [4]:
def outer():
x = 1 # global variabel for inner and local for outer.
def inner(): # local function/scope of outer.
return x
return inner()
In [6]:
print outer() # 1,no output
print inner() # 1,no output
In [7]:
#
def fun():
pass
print fun
print type(fun)
fun
Out[7]:
In [10]:
# function closures : During defination of function,the function address holds all the variable
# available both locally and globally.
# decorators.
def outer():
x = 1 # global variabel for inner and local for outer.
def inner(): # local function/scope of outer.
return x
print locals()
return inner # address of function inner
In [12]:
foo = outer()
print x
In [13]:
'''
def inner(): # local function/scope of outer.
return x
'''
print foo
print foo()
In [14]:
# map,filter and lambda
In [15]:
# map
print help(map)
In [17]:
def square(a):
return a * a
# square
print square(2)
print square(3)
print square(4)
In [18]:
print map(square,[1,4,6,8,12,14,17,19])
In [19]:
# filter
print help(filter)
In [20]:
def even(a):
if a % 2 == 0:
return 'even'
print even(2) # true
print even(3) # false
In [21]:
print filter(even,[1,2,3,4,5,6,7,8,9,10])
In [22]:
# other examples
print map(square,[1,4,6,8,12,14,17,19]) # output after applying sequence to function.
print filter(square,[1,4,6,8,12,14,17,19]) # give you elementf of sequence for function being true.
In [23]:
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])
In [25]:
# lambda
# nameless function.
print map(square,[1,4,6,8,12,14,17,19])
print map(lambda a:a*a,[1,4,6,8,12,14,17,19])
In [26]:
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])
In [ ]:
# exercises
# https://github.com/zhiwehu/Python-programming-exercises/blob/master/100%2B%20Python%20challenging%20programming%20exercises.txt