Learn practical skills, build real-world projects, and advance your career

Functions are ´reusable set of instructions. They take in arguments, execute instructions and often return a value. Functions are of two types namely, built-in and user defined.

Syntax for user defined functions:

def function_name(arguments): \

statement 1   \
statement 2   \
.             \
.             \
.             \
statement nth

return

main body

function_name(arguments)

def say_hello(name):
    print("Hello",name)
    print("How are you?")
person1 = "Michael"
say_hello(person1)
Hello Michael How are you?
def filter_even_odd(list):
    result_list_even = []
    result_list_odd = []
    for i in range(len(list)):
        if list[i] % 2 == 0:
            print("The value at position {} in the list is {} and is even".format(i, list[i]))
            result_list_even.append(list[i])
        else:
            print("The value at position {} in the list is {} and is odd".format(i, list[i],))
            result_list_odd.append(list[i])
    return result_list_even, result_list_odd
random_list = [45,23,54,78,1,5,99,150,143,176,12,56]
sorted_list = filter_even_odd(random_list)
print("The sorted list :", sorted_list)
The value at position 0 in the list is 45 and is odd The value at position 1 in the list is 23 and is odd The value at position 2 in the list is 54 and is even The value at position 3 in the list is 78 and is even The value at position 4 in the list is 1 and is odd The value at position 5 in the list is 5 and is odd The value at position 6 in the list is 99 and is odd The value at position 7 in the list is 150 and is even The value at position 8 in the list is 143 and is odd The value at position 9 in the list is 176 and is even The value at position 10 in the list is 12 and is even The value at position 11 in the list is 56 and is even The sorted list : ([54, 78, 150, 176, 12, 56], [45, 23, 1, 5, 99, 143])