Tuesday 6 October 2020

Part Three: Functions: Introduction

 We have come across some built-in functions in our Python 3 programming journey. These functions include print() and input(). These functions were already defined and programmed somewhere within Python and we did not need to know what happens behind the scenes but whenever we invoked them, they work as defined.

In this part of the course, we are going to be looking at user-defined functions. That is functions we can create ourselves as programmers and which we can invoke anywhere in our program to carry out some tasks similar to how we would invoke a built-in function like print() or input().

When writing a function we start with the def keyword then followed by the function name then followed by a colon. Then the statements follow under that with indentations. For example

          def  function_name(parameters):

                   statement 1

                   statement 2                                                                                                 

                                           

                  

Let us try an example by writing a function to display the ‘Hello world’ message

 

def message():
    print('Hello world')

message()

when the code above is run, message() prints ‘Hello world’.

We can add more lines of code under the message function and that would be executed when message() function is called.

def message():
    print('Hello world')
    print('testing functions in Python')
    print('addition', 3 + 5)
    print('subtraction', 8 - 3)
    print('Thank you')

message()

When message() function is called in the code above, all the statements within the function are executed.

The advantage of this is you can define a function at the beginning of your program and then call it many times later in your program without having to write the whole code over and over again.

We could also return a value in our function and include a parameter. For example;

def square(x):
    return x ** x

print(square(2))

In the function above, x is the parameter introduced into the function and the function returns the square of x. So whenever the function is called, it returns the square of the parameter.

We can as well have multiple parameters in our function. Example;

def addition(a, b):
    return a + b

print(addition(2, 3))


The function above takes two parameters, a and b, and returns the sum of the parameters. In the example above two arguments, 2 and 3 were provided and the sum 5 was returned.

 

 

No comments:

Post a Comment