Functions are a way of writing code whereby you group together a set of "tasks". Therefore, instead of writing tasks individually, multiple times, you simply use the Function that houses the set of tasks.
This means if you have a repetitive task, you do not have to write the code over and over. Just write the code into a function and use the function to do the task.
Functions will be building blocks for constructing complex codes.
Structure of a function
Functions start with a def
, followed by a function name and parenthesis, the docstring (optional), the function statements (i.e. codes) and ending with either return
, pass, or nothing at all. Watch the accompanying video for a more detailed explanation.
Python functions usually looks something like this:
Syntax
def functionname(arguments): """This is the docstring that explains what this function is supposed to do""" function statements return
Calling a function
To use the function we simply call its name by writing functionname()
Example
In this example, my function name is hello.
Note that this function does not have a return
statement, otherwise known as a void function.
Here is another example of a void function. The function rounds any decimal number that a user inputs to 3 decimal places.
From 1.41 to 4.58
You are expected to comply with University policies and guidelines namely, Appropriate Use of Information Resources Policy, IT Usage Policy and Social Media Policy. Users will be personally liable for any infringement of Copyright and Licensing laws. Unless otherwise stated, all guide content is licensed by CC BY-NC 4.0.