BYU logo Computer Science

To start this guide, download this zip file.

Return

So far we have been calling functions and not expecting anything back. For example, when we define and call a function called paint_green():

def paint_green(bit):
    while bit.can_move_front():
        bit.paint('green')


@Bit.empty_world(5, 3)
def go(bit):
    paint_green(bit)

We are essentially saying “run the paint_green() function”, without expecting anything back:

the go() function calls the paint_green() function

Functions can all return values back to the place where they were called:

def keep_going(bit):
    if bit.is_on_blue():
        return False

    else:
        return True


@Bit.empty_world(5, 3)
def go(bit):
    while keep_going(bit):
        bit.move()

Here, the code is saying, “run the keep_going() function, and give me back either True or False:

the go() function calls the keep_going() function and expects a return value

TO return a value from a function, use the return statement. The value after return is sent to the place where you called the function. For now, we will be using return True and return False, and we will show you additional examples later.

Example

Let’s see return in action. In this problem, Bit tries to follow a straight, blue trail:

a straight, blue trail for Bit to follow

Sometimes the trail is longer:

a straight, blue trail that goes to the edge of the world

Download the zip file linked above and store it in your bit folder. Find the file called blue_trail:

from byubit import Bit


def keep_going(bit):
    if not bit.can_move_front():
        return False

    elif not bit.is_on_blue():
        return False

    else:
        return True


@Bit.worlds('blue-trail', 'blue-trail2')
def run(bit):
    while keep_going(bit):
        bit.move()


if __name__ == '__main__':
    run(Bit.new_bit)

The keep_going() function returns False if (a) Bit is not clear in front or (b) the current square is not blue. It returns True in all other cases.

Run this code and step through it with the buttons to understand how it works.