Define a function

Python is an imperative language. In Python you can define procedures and functions using the same syntax for both. There is only one keyword: “def”. A function can calculate and return one or more results, while a procedure do not return anything. A procedure and a function is call using the name and parentheses with or without parameter values.

A function definition is using keyword def, followed by the name and the parameters. The body of the function start at the next line, and must be indented. The function result type is not declared.


def fib(n):    
     """Print a Fibonacci series up to n."""
     a, b = 0, 1
     while a < n:
         print(a, end=' ')
         a, b = b, a+b


0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

Function description

The description of a function can be created using triple quotes and string as the first statement after the function declaration. This can be used to find information about function using: help(<function_name>)

Functions with result

Functions can return a result. In the next example I calculate a factorial using a recursive function then I return a result:

# calculate factorial of n
def factorial(n):
    if n==0:
         return 1
         return n*factorial(n-1)

# call factorial function and capture result

This will print: 120

Function parameters

Function parameters are not mandatory. However to execute a function the parenthesis must be used after the function even if there are no parameters defined. Parameters can have initial values. In this case the parameters are optional and do not have to be mentioned in the function call.

Read next: Namespaces