How to define and call Python function with return examples

The function in Python

As in other programming languages, Python provides a way to create and use the functions in its programs.

See an example of function

A Python function is a block of code that may take one or more input parameters, executes and may return a value. Functions can be used in Python programs repeatedly. A function’s code will only be executed once this is called.

There are plenty of built-in functions, however, programmers can create their own. Functions make the life of programmers quite easier in that you don’t have to write the code again and again for the same purpose.

You even don’t need to go through the code, if a function is written by some other programmer, like Python built-in functions.

Writing your own functions

There are two parts of Python functions:

  1. Defining a function
  2. Calling a function

Syntax of creating or defining a function

def function_name ( params ):

   “function’s purpose statements or instructions etc.”

  # Statements to be executed

   return [expression]

So what above lines are doing?

  • A function is defined by using the def keyword.
  • The def is followed by function name and parenthesis.
  • Any input parameters are given within the parenthesis, followed by ‘:’
  • The first line of the function can be documentation containing the purpose or instruction of the function (optional).
  • After that, statements to be executed with indentation.
  • The return statement may contain the parameter, sending back to the caller of the function. If no argument is given in return statement, it will be taken as return nothing.

Defining a function example

The example below defines a simple function, that takes two parameters as input, sums up and print the sum of two. As such, the function is only defined and not called, if you run this code it will display nothing.

Calling a function example

Now we will call the above function, where we will send two parameters. The complete code of creating and calling the function is:

See this example online

The output will be:

25

Using Python return statement example

A function in the following example simply takes two parameters (numbers), sum those up and returns one expression.

See this example online

The output will be:

25

Further Reading: Class in Python