Learn

We can use functions to organize our code and make it easier to understand. One main function can call slightly smaller functions that each have a specific goal. Those functions can call more specific functions if necessary. Each function does a part of a larger task.

Imagine we were making a program that creates a random bag of marbles and describes it to us. We would need to create and describe each marble. We could have a main program that looks like:

def main(): random_bag = create_random_bag() display_bag()

Our create_random_bag function might look like:

def create_random_bag(): marble1 = create_random_marble() marble2 = create_random_marble() marble3 = create_random_marble() return [marble1, marble2, marble3]

The create_random_marble might contain logic for what the marble looks like, and on the program would go, describing more and more detailed logic. With this kind of structure, our programs become more organized and easy to read.

Now, we’ll practice organizing a program by creating functions.

Instructions

Codey has to move pretty far this time. While we could just load up function A with a lot of blocks and call it multiple times, let’s try to make a hierarchy.

Try defining function A with multiple calls to Move Right, then a function B with multiple calls to function A. Then call function B multiple times.

Throughout this course we will use Blockly commands to guide Codey towards their goal. Drag the commands into the right hand box and connect them together to make a program.

For this exercise, combine the movement commands together to have Codey move onto the flag.

Hint
Try putting 2 `Move Right` Calls in Function `A`, 3 Function `A` calls in Function `B`, and then call Function `B` twice.
Solution
Define Function A: Move Right Move Right Define Function B: Call Function A Call Function A Call Function A Call Function B Call Function B

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?