Python : Crash Course Part 11 – Functions

We use the def keyword to define a function in python, followed by a function name and parameters. Let me show you a basic function in python :

In [1]: def my_func (param1) :
In [2]: my_func('hello')

Let’s see some more examples. We can use the + operator to concatenate the string ‘Hello’ with the input parameter which is name. In case we do not pass any parameter to the function, the output returned is Default Name

In [3]: def my_func (name='Default Name') :
               print('Hello' + name)
In [4]: my_func('Analytics')
        Hello Analytics
In [5]: my_func()
        Default Name

In case we have to return a value in a function after the computing the results, we can do that using the return statement within the function as shown below :

In [6]: def square(num): 
        This function squares a number
        return num**2
In [7]: output = square(2)
In [8]: output
Out[9]: 4

Note the use of double quote is used 3 times to enter comment text within the function. Now that we know the basics of functions, lets move on to map function.

Lets say we have a sequence :

In [10]: seq=[1,2,3,4,5]

If we have to lets say use the above function square to square every number in our sequence above, we can use the map function as shown below :

In [11]: map(square,seq)
Out[12]:<map at 0x17ce8b6d550>

The above map is now saved at a memory location. If we have to retrieve the output we will have to cast the map function to a list as shown below :

In [13]: list(map(square,seq))
Out[14]: [1,4,9,16,25]

If you have to rewrite the def function as we discussed above to a much simpler way of computing / calculating desired results we could use the lambda expression:

In [15]: t=lambda(var:var*2)
In [16]: t(6)
Out[17]: 12

But mostly we will be using the lambda expression in our map function as shown below:

In [18]: seq=[1,2,3]
In [19]: list(map(lambda var:var*3,seq))
Out[20]: [3,6,9]

In [19] statement basically multiplies numbers in the sequence ( seq ) by 3.

Lets take a look at the filter function, as the name suggests the function would retrieve values which are true/satisfied/met.

In [21]: list(filter(lambda: num:num%2 == 0,seq))
Out[22]: [2]

The modulus function above retrieving a 0 is true only for the integer 2 and false for 1 and 3, hence the output is integer 2.

Let’s move on to methods in python. If you have any questions or suggestions, please let me know in the comments section below.