design, write and debug programs that accomplish specific goals, including controlling or simulating physical systems; solve problems by decomposing them into smaller parts.

3.1a

LO: To write my own function.

Recap basic commands in Reeborg, complete the world Simple Maze.

Depending on how fast the children are at completing the maze you may want to stop them before they finish.

#simple maze
turn_left()
move()
move()
turn_left()
turn_left()
turn_left()
move()
turn_left()
turn_left()
turn_left()

			

Stopping here, for example, you might want to ask the children what they wished Reeborg could do...
Being able to turn right would save typing out three turn_left() commands.


Now is the time to teach Reeborg how to turn right! We are going to introduce the concept of functions as a way of teaching Reeborg how to do something.

#basic form of a function

def name():
    #do something

			

Let's break this down:

Lets look at an example:

#a function to turn right

def turn_right():
    turn_left()
    turn_left()
    turn_left()

			

There is one final, very important lesson about functions; so far we have written one that teaches Reeborg to turn right, Reeborg knows but we have to write a command to make Reeborg do it - that command is simply the name we have given the function!

#a function to turn right

def turn_right():
    turn_left()
    turn_left()
    turn_left()

#to make Reeborg 'do' the function we need to 'call' the function by writing it's name
turn_right()

			

Notice that when we 'call' the function it must not be indented like the instructions or it will be seen as part of the function. This is how our Simple Maze world example would now look:

#simple maze

#first define the function (teach it to Reeborg)
def turn_right():
    turn_left()
    turn_left()
    turn_left()
#remove the indent as we have finished teaching Reeborg

turn_left()
move()
move()
turn_right() #now we call the function to perform the action
move()
turn_right()

			

If you use the step option when running your code you will be able to see the code jumping back to the function definition every time the function is called.

* - There are some other rules about naming functions and other wonderful things that you can learn about in the help page.

Code Examples

Resources