Functions

A function allows a developer to create a set of statements to carry out a task that can then be called any number of times from within a program. This allows the program structure to be more readable by reducing it into logical blocks of code that each perform their own task. The top level of the code then just controls the flow between these function calls.

In other languages you might hear functions referred to as subprograms, procedures, routines or subroutines.

To create a function you use the syntax:

def function_name():
    // indented section
    // of code to run

The def keyword tells Python you want to define a function and then you give a name to the function that explains what it is doing.

To call a function you then use the function name and parenthesis.

function_name()

Try this out now. Make a simple function to print a line of text and call it a couple of times.

def hello():
    print("Hello world")

print("Program starts")
hello()
hello()
print("Program ends")
Program starts
Hello world
Hello world
Program ends

Passing values into functions

If you need to pass the function any arguments/parameters they can be added into the parentheses as a comma separated collection:

def function_name(argument1, argument2):
    print("The value of the first parameter is", argument1)
    print("The value of the second parameter is", argument2)

You would then call the function as such:

function_name("Argument 1 is a string", 12345)

Let’s try it out:

def loop_text(text_to_show, times_to_repeat):
    for counter in range(times_to_repeat):
        print(text_to_show)

# Top Level Program

print("Program starts")
loop_text("Hello world!", 6)
print("Program ends")
Program starts
Hello world!
Hello world!
Hello world!
Hello world!
Hello world!
Hello world!
Program ends

Returning values from functions

The function can return values too using the return statement.

def add_two_numbers(number1, number2):
    total = number1 + number2
    return total

print("Program starts")
number1 = 10
number2 = 5
result = add_two_numbers(number1, number2)
print(result)
print("Program ends")
Program starts
15
Program ends

If your function returns a value, you need to make sure that all paths through the function return a value. The following code would cause problems.

def check_number_greater_than_10(number_to_check):
    if number_to_check > 10:
        return "Number is greater than 10"
    else:
        print("Number is not greater than 10")

result = check_number_greater_than_10(13)

If the number was not greater than 10 then a return line is never reached. The result would be a null or None value which could cause problems if your code was expecting a value. Here are two ways to avoid this.

1 – Always make sure there is a return line in each path.

def check_number_greater_than_10(number_to_check):
    if number_to_check > 10:
        return "Number is greater than 10"
    else:
        return "Number is not greater than 10"

result = check_number_greater_than_10(13)

2 – Always return a value at the end of a function

def check_number_greater_than_10(number_to_check):
    comment = "Number is not greater than 10"
    if number_to_check > 10:
        comment = "Number is greater than 10"
    
    return comment

result = check_number_greater_than_10(13)

In the second option the function will always return a value at the end. You set a default value to be returned and then override that within the function. This way no matter what happens in your function code it will always end up at the return line.

Returning multiple values

In Python you can return multiple values in a return statement. You simply provide a comma separated list of variables to accept the returned values.

def add_two_numbers_and_average(number1, number2):
    total = number1 + number2
    average = total / 2
    return total, average

print("Program starts")
number1 = 10
number2 = 5
result, average = add_two_numbers_and_average(number1, number2)
print(result)
print(average)
print("Program ends")
Program starts
15
7.5
Program ends
def add_two_numbers_and_average(number1, number2):
    total = number1 + number2
    average = total / 2
    return total, average

number1 = 10
number2 = 5
result, average = add_two_numbers_and_average(number1, number2)
print(result)
print(average)

The program does not understand what the variable is meant to do so it is the order in which the variables are returned that matches them into the outer variables. In the example above, the variable inside the function total is stored in the variable outside the function called result. This is because total is the first variable after the return keyword, and result is the first variable on the line where the function is called.

In most programming languages if you wanted to send multiple bits of data back you’d set up an array or class object to return because you wouldn’t be able to send multiple values in the return.


Procedures

A procedure is a function that does not return a value. Look at the examples below.

def print_area(length, breadth):
    area = length * breadth
    print(area)


shape_length = 10
shape_breadth = 3
print_area(shape_length, shape_breadth)
def calculate_area(length, breadth):
    area = length * breadth
    return area

shape_length = 10
shape_breadth = 3
area = calculate_area(shape_length, shape_breadth)
print(area)

print_area is a procedure. Nothing is returned and it has no impact on the program’s execution.

calculate_area is a function. It returns a value which can be used within the program.


Formal vs actual parameters

The formal parameter is how a variable is called within a function.

The actual parameter is how a variable is called in the main program outside of the function.

def print_name(fname, lname):
    print(fname + " " + lname)

first_name = "John"
last_name = "Smith"

print_name(first_name, last_name)

In this example the formal parameters are fname and lname.

The actual parameters are first_name and last_name.

Next: Variable scope

Report a Glow concern
Cookie policy  Privacy policy

Glow Blogs uses cookies to enhance your experience on our service. By using this service or closing this message you consent to our use of those cookies. Please read our Cookie Policy.