Python - tutorial - 09/14

functions - lambda - arrays

Revision:


Python - functions

Creating a function: in Python a function is defined using the "def" keyword.

Example 1: create a function

        def my_function():
            print("Hello from a function")
    

Calling a function: to call a function, use the function name followed by parenthesis.

Example 2: call a function

        def my_function():
            print("Hello from a function")
        my_function()
    

Arguments: information can be passed into functions as arguments. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

Example 3: arguments

        def my_function(fname):
            print(fname + " Refsnes")
        my_function("Emil")
        my_function("Tobias")
        my_function("Linus")
    

Number of arguments: by default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.

Example 4: this function expects 2 arguments, and gets 2 arguments:

        def my_function(fname, lname):
            print(fname + " " + lname)
        my_function("Emil", "Refsnes")
    

Arbitrary arguments, *args: if you do not know how many arguments will be passed into your function, a * before the parameter name in the function definition. This way the function will receive a tuple of arguments, and can access the items accordingly.

Example 5: if the number of arguments is unknown, add a * before the parameter name:

        def my_function(*kids):
            print("The youngest child is " + kids[2])
        my_function("Emil", "Tobias", "Linus")
    

Keyword arguments: you can also send arguments with the key = value syntax. This way the order of the arguments does not matter.

Example 6: keyword arguments

        def my_function(child3, child2, child1):
            print("The youngest child is " + child3)
        my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
    

Arbitrary keyword arguments, **kwargs: If you do not know how many keyword arguments will be passed into your function, add two asterisk "**" before the parameter name in the function definition.This way the function will receive a dictionary of arguments, and can access the items accordingly.

Example 7: If the number of keyword arguments is unknown, add a double ** before the parameter name:

        def my_function(**kid):
            print("His last name is " + kid["lname"])
        my_function(fname = "Tobias", lname = "Refsnes")
    

Default parameter value: if we call the function without argument, it uses the default value.

Example 8:how to use a default parameter value.

        def my_function(country = "Norway"):
            print("I am from " + country)
        my_function("Sweden")
        my_function("India")
        my_function()
        my_function("Brazil")
    

Passing a list as an argument: you can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function. E.g. if you send a List as an argument, it will still be a List when it reaches the function.

Example 9: passing a list as an argument:

        def my_function(food):
            for x in food:
                print(x)
        fruits = ["apple", "banana", "cherry"]
        my_function(fruits)
    

Return values: to let a function return a value, use the return statement.

Example 10: return values.

        def my_function(x):
            return 5 * x
        print(my_function(3))
        print(my_function(5))
        print(my_function(9))
    

The pass statement: "function" definitions cannot be empty, but if you for some reason have a function definition with no content, put in the pass statement to avoid getting an error.

Example 11: pass statement

        def myfunction():
            pass
    

Recursion: Python also accepts function recursion, which means a defined function can call itself.

Recursion is a common mathematical and programming concept. It means that a function calls itself.
This has the benefit of meaning that you can loop through data to reach a result.
The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never terminates, or one that uses excess amounts of memory or processor power.
However, when written correctly recursion can be a very efficient and mathematically-elegant approach to programming.

Example 12: recursion example:

        def tri_recursion(k):
            if(k > 0):
                result = k + tri_recursion(k - 1)
                print(result)
            else:
                result = 0
            return result
        print("\n\nRecursion Example Results")
        tri_recursion(6)
    


Python - lambda

A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression.

Syntax: lambda arguments : expression

Example 13: add 10 to argument a, and return the result:

        x = lambda a : a + 10
        print(x(5)) # 15
    

Arguments: lambda functions can take any number of arguments.

Example 14: multiply 'argument a' with 'argument b' and return the result:

        x = lambda a, b : a * b
        print(x(5, 6)) # 30
    

Example 15: summarize argument a, b, and c and return the result:

        x = lambda a, b, c : a + b + c
        print(x(5, 6, 2)) # 13
    

Why use lambda functions? The power of lambda is better shown when you use them as an anonymous function inside another function. Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown number:

 def myfunc(n):
        return lambda a : a * n

Use that function definition to make a function that always doubles the number you send in.

Example 16: lambda function in function:

        def myfunc(n):
            return lambda a : a * n
        mydoubler = myfunc(2)
        print(mydoubler(11)) # 22
    

Or, use the same function definition to make a function that always triples the number you send in.

Example 17: triple the number:

        def myfunc(n):
            return lambda a : a * n
        mytripler = myfunc(3)
        print(mytripler(11)) # 33
    

Or, use the same function definition to make both functions, in the same program:

Example 18: make both functions

        def myfunc(n):
            return lambda a : a * n
        mydoubler = myfunc(2)
        mytripler = myfunc(3)
        print(mydoubler(11))
        print(mytripler(11))
    


Python - arrays

Note: Python does not have built-in support for arrays, but Python lists can be used instead. To work with arrays in Python you will have to import a library, like the NumPy library.

Arrays: arrays are used to store multiple values in one single variable.

Example 19: create an array containing car names:

        cars = ["Ford", "Volvo", "BMW"]
    

Access the elements of an array: you refer to an array element by referring to the index number.

Example 20: get the value of the first array item:

        x = cars[0]
    

Example 21: modify the value of the first array item:

        cars[0] = "Toyota" 
    

The Length of an array: ue the len() method to return the length of an array (the number of elements in an array).

Example 22: return the number of elements in the cars array:

        x = len(cars)
    

Looping array elements: you can use the "for in" loop to loop through all the elements of an array.

Example 23: print each item in the cars array:

        for x in cars:
            print(x)
    

Adding array elements: you can use the append() method to add an element to an array.

Example 24: add one more element to the cars array:

        cars.append("Honda")
    

Removing array elements: you can use the pop() method to remove an element from the array. You can also use the remove() method to remove an element from the array.

Example 25: delete the second element of the cars array:

        cars.pop(1)
    

Example 26: delete the element that has the value "Volvo":

        cars.remove("Volvo")
    

Array methods: Python has a set of built-in methods that you can use on lists/arrays.

Method - Description
append() - Adds an element at the end of the list
clear() - Removes all the elements from the list
copy() - Returns a copy of the list
count() - Returns the number of elements with the specified value
extend() - Add the elements of a list (or any iterable), to the end of the current list
index() - Returns the index of the first element with the specified value
insert() - Adds an element at the specified position
pop() - Removes the element at the specified position
remove() - Removes the first item with the specified value
reverse() - Reverses the order of the list
sort() - Sorts the list