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 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! |
| Statement about functions | True 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. | ? |
def beep():
print("Beep!")
print("Ready") def hello():
print("Hi crew")
print("Status green")
print("Start")
hello()
hello()
print("End") | Statement | True 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. | ? |
You wrote real Python functions! Tomorrow you will hand them values to work with.