Python Programming by Example (2015)

4. Functions

This chapter explains how to create function using Python.

4.1 Creating A Simple Function

Declaring function in Python has format as follows.

def foo():

    print('foo()')

You can call this function foo() on your program.

4.2 Function with Parameters and Returning Value

Sometimes you want to create a function with a parameter. You can implement it as follows.

def calculate(val_a, val_b):

    val = val_a * val_b

    return val

4.3 Function with Multiple Returning Values

A function can return multiple returning values in Python. For instance, we return three values in Python function. A sample code can be written as below.

def perform(num):

    d = num * 5

    return d, d + 5, d - 2

4.4 Recursion Function

Recursion function is a function where the solution to a problem depends on solutions to smaller instances of the same problem (as opposed to iteration). For illustration, we can implement Fibonacci problem using Python. 

The following is a sample code for Fibonacci solution in Python.

def fibonacci(n):

    if n == 0:

        return 0

    elif n == 1:

        return 1

    else:

        return fibonacci(n-1) + fibonacci(n-2)

4.5 Testing

We can write code again from section 4.1 to 4.4 and use them in on ch04_01.py file.

def foo():

    print('foo()')

def calculate(val_a, val_b):

    val = val_a * val_b

    return val

def perform(num):

    d = num * 5

    return d, d + 5, d - 2

def fibonacci(n):

    if n == 0:

        return 0

    elif n == 1:

        return 1

    else:

        return fibonacci(n-1) + fibonacci(n-2)

foo()

m = calculate(10, 5)

print(m)

a, b, c = perform(5)

print(a)

print(b)

print(c)

res = fibonacci(10)

print(res)

Save and run the program.

python3 ch04_01.py

A sample of program output:

p4-1