← Back to course
Code Crew G4 / Week 10 / Monday
1/6
Week 10 Β· Functions that return

Monday

Name a group of lines
// Name it, feed it, get an answer
⏱ about 15 min

Monday: Name a group of lines

Every launch starts with the same countdown: three, two, one, liftoff. Rocket has copied the same four print lines into his program six times. Then the crew asks him to add a beep before liftoff.

"Now I have to fix it in six places," he groans.

Raven remembers last year. "What do you notice? We gave a group of steps a name in pseudocode." Nova flashes a familiar word: function. "Would you like a hint? Python has a short word for making one."

def makes a function

def gives a group of lines a name. The lines are indented under the def line.

Defining a function does not run it. Calling the function runs it. To call it, write its name with brackets.

def countdown():
    print("3")
    print("2")
    print("1")
    print("Liftoff!")

countdown()
print("Shuttle away")
countdown()
The screen shows
3
2
1
Liftoff!
Shuttle away
3
2
1
Liftoff!
  • The def line has the name, empty brackets and a colon.
  • The blank line is just for reading. Python skips it.
  • Now Rocket can add the beep in one place, and every call gets it.
How many lines show on the screen if countdown() is called 3 times and nothing else prints?
WHY THIS EXERCISEEvery call runs every line in the function. That is how functions save work.
Statement about functionsTrue or false?
The def line ends with a colon.?
Defining a function runs it right away.?
countdown() calls the function.?
A function can be called more than once.?
WHY THIS EXERCISEDefine once, call many times. That is the big idea of functions.
def beep():
    print("Beep!")

print("Ready")
WAS IT CALLED?
  • Read the question.
  • Tap your answer.
What does the program above show?
Try it
Pick a short routine, like a cheer with three lines.
Write it as a def. Then write two calls.

Practice lab: define once, call twice

def hello():
    print("Hi crew")
    print("Status green")

print("Start")
hello()
hello()
print("End")
How many lines show on the screen?
What is the first line on the screen?
What is the last line on the screen?
How many times is hello called?
DEFINE OR CALL?
  • Read the question.
  • Tap your answer.
Which line defines a function named alarm?
Which line calls alarm?
Where do the lines of a function go?
StatementTrue or false?
Python skips the blank line in a program.?
A function runs when it is defined.?
A call needs brackets.?
A function body has no indent.?
WHY THIS EXERCISEDefining stores the steps. Calling runs them.
A function prints 2 lines. It is called 5 times. How many lines show?
WHY THIS EXERCISE5 calls times 2 lines makes 10 lines.

You wrote real Python functions! Tomorrow you will hand them values to work with.