Topic 8: Functions

A function is a block of code grouped with a name and performs a task. Functions allow for blocks of code to be used many times in a program without having to duplicate code. It also allows large, complex programs to be broken down into small, manageable sub-tasks. Each sub-task is solved by a function, and thus different people can write different functions.

Function definition

Rules for function names are the same as for variables. Good idea to use meaningful names that describe the function’s purpose. The verb is preferable.

Syntax:
  1. def function_name([parameterList]):
  2. statement

Memory locations in parameterList are called formal parameters - each store an item of information passed to the function when it is called.

Example 1: with no parameter
    1. def function_example1():
    2. print(“This is a function without a parameter”)
Example 2: with one parameter
    1. def function_example2(str):
    2. print(str)

Calling a Function

A function must be called (invoked) to perform its task. The name of the function is used to call the function.

Syntax:
functionName([argumentList]);
  • argumentList is list of actual arguments (if any)
  • An actual argument can be a variable, named constant, literal constant, or keyword
Example 1
    1. function_example1()
Example 2
    1. function_example2(“This is a function with a parameter”)

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.

Example: if you send a List as an argument, it will still be a List when it reaches the function
    1. def my_function(food):
    2. for x in food:
    3. print(x)

    4. fruits = ["apple", "banana", "orange"]

    5. my_function(fruits)