← Back to course
Code Crew G3 / Week 05 / Thursday
4/6
Week 05 Β· Functions

Thursday

// Steps with names

Thursday: Function Stack

Rocket writes a function to clean teeth. Inside it, he calls brush and rinse, then brush and rinse again. "Functions inside functions!" he cheers.

Raven reads it slowly. "What do you notice about brush?" she asks. "It shows up more than once," Rocket says.

Nova lights up each call. "Count one line at a time. Then look for a chunk that repeats." Let's help them count the calls.

Functions can call OTHER functions. Read this carefully:

function brush():    move toothbrush 20 times
function rinse():    sip water, swish, spit

function clean_teeth():
    brush()
    rinse()
    brush()
    rinse()

Count it

How many times does brush() run? ____
How many times does rinse() run? ____
If brush takes 30 sec, total time? ____ sec

Spot the Repeat

Look at this messy code. There's a repeated chunk that should be a function.

Underline the repeat. Give it a NAME.

open the door
say hello
wave hand
...
open the door
say hello
wave hand
...
open the door
say hello
wave hand
Function name:
What it does:

Functions Calling Functions

A function can call another function. To count, start with the smallest one.

function clap2():
    clap
    clap

function cheer():
    clap2()
    jump
    clap2()
How many claps happen when cheer() runs?
How many jumps happen when cheer() runs?
cheer() is called 3 times. How many claps in all?
BUILD WITH BLOCKS
  • Read the question.
  • Tap your answer.
Which function is the smallest building block?
clap2 changes to 3 claps. How many claps in one cheer() now?
Why make clap2 a function?
A program repeats open door, say hello, wave. What should you make?
StatementTrue or false?
A function can call another function.?
Changing clap2 changes every cheer().?
A repeated chunk of steps is a clue for a function.?
cheer() can run without running clap2().?
WHY THIS EXERCISEFunctions inside functions let small fixes reach the whole program.
hop() means jump 2 times. bounce() calls hop() 5 times. How many jumps does bounce() make?
WHY THIS EXERCISEMultiply the steps inside by the number of calls.
Try it
Make a cheer with a grown-up.
Name a small move, like stomp2().
Build a bigger cheer that calls it twice.

Quick Check

hop() means jump 4 times. dance() calls hop() 3 times. How many jumps happen when dance() runs? ____
WHY THIS EXERCISEWhen one function calls another, all the inner steps run each time. Programmers trace calls like this to count work.
← Wednesday