Jun 24, 2018

Python Functions

#!/usr/local/bin/python2.7

'''
    File name: functions_python.py
    Author: Prabhath Kota
    Date: June 22, 2018
    Python Version: 2.7
'''

'''
Functions are meant to re-use & reduce repeated code
Python functions are passed by reference by default
Non-default argument should never follows default argument
ie.,
    def getEvenOddNumbers(type="even", list): #Wrong
    def getEvenOddNumbers(list, type="even", list): Right
Python Fucntons support Default arguments
Anonymous functions
Variables that are defined inside a function body have a local scope, and those defined outside have a global scope.
Return statements
'''

def getEvenOddNumbers(list=[], type="even"):
    result_list = []
    try:
        if type == 'odd':
            result_list = [i for i in list if i%2 != 0]
        else:
            result_list = [i for i in list if i%2 == 0]
    except Exception, e:
        print '**** Error: ' + str(e)   
    return result_list

def sumUpAll(*kargs):
    print kargs
    return_val = 0
    for each_argument in kargs:
        return_val += each_argument
    return return_val

#Anonymous Fucntion
sum_func = lambda arg1, arg2: arg1 + arg2

#When you run this as a stand alone script, the following will get executed
#When you import this file, the following will not get executed
if __name__ == "__main__":
    localList = [3, 5, 7, 10, 20 , 36, 98, 33, 23, 76]
    print '------------Function - with default args-------------------'
    print  localList
    print getEvenOddNumbers(localList)
    print '------------Function - with default & non - default args-------------------'
    print getEvenOddNumbers(localList, "odd")
    print '------------Function - with non-default args-------------------'
    print getEvenOddNumbers(type="odd", list=localList)
    localList1 = ['Hi', 'Friend', 'lets', 'rock']
    print localList1
    print getEvenOddNumbers(localList1)
    print '------------Function variable arguments-------------------'
    print sumUpAll(10)
    print sumUpAll(10, 20)
    print sumUpAll(10, 20, 30)
    print sumUpAll(10, 20, 30, 40)
    print sumUpAll(10, 20, 30, 40, 50)
    print '------------Anonymous Function-------------------'
    print sum_func(100, 200)
    print sum_func('India', 'is Great')
    print sum_func([10,20], [30,40])


Output:

------------Function - with default args-------------------
[3, 5, 7, 10, 20, 36, 98, 33, 23, 76]
[10, 20, 36, 98, 76]
------------Function - with default & non - default args-------------------
[3, 5, 7, 33, 23]
------------Function - with non-default args-------------------
[3, 5, 7, 33, 23]
['Hi', 'Friend', 'lets', 'rock']
**** Error: not all arguments converted during string formatting
[]
------------Function variable arguments-------------------
(10,)
10
(10, 20)
30
(10, 20, 30)
60
(10, 20, 30, 40)
100
(10, 20, 30, 40, 50)
150
------------Anonymous Function-------------------
300
Indiais Great
[10, 20, 30, 40]
[Finished in 0.2s]

No comments:

Post a Comment