Lesson 4.1
Define and call a function
Part 4: FunctionsReading, about 5 min2 exercises in this lesson
Java answers can't run on Spine yet. You can still read Java, trace it, and put an answer's lines in order.
Define and call a function
By the end of this you will be able to define a function that does one job and call it from the main part of your program.
Every program so far puts all its code in one place. A function is a named block of code that you can call whenever you need it. Defining a function does not run it: the code inside runs only when you call the function by name.
Defining and calling
def greet():
print("Hello!")
print("Welcome.")
greet()
greet()public static void main(String[] args) {
greet();
greet();
}
static void greet() {
System.out.println("Hello!");
System.out.println("Welcome.");
}This prints the two greeting lines twice (four lines in all). The function greet is defined once and called twice.
In Python, def starts the definition, and the body is indented. In Java, the function (called a method) is written outside main but inside the class, with static void before its name. void means it does not send a value back. Only main and the method are shown here: the class around them is the same as in your first program.
What runs, and when
The computer still runs one statement at a time, but a call makes it jump. In the program above:
- The body of
greetdoes not run where it is written. It waits to be called. - The first call in the main code runs the body:
Hello!, thenWelcome.. - When the body ends, the program carries on from just after that call, which is the second call.
- The second call runs the body again, and then the program ends.
So the body is written once but runs twice, once for each call. In Python, the def must run before the first call does, so it goes above the main code: the file runs from the top, and a name cannot be used before it exists. In Java, a method can sit above or below main.
Why use a function
- You avoid repeating the same code. If the greeting changes, you fix it in one place.
- The main code reads like a plan: "greet, then greet again" is clearer than four lines of print calls.
- You can test the function on its own, apart from the rest of the program.
A function that does one job well is easier to read, test, and change than one that does several things at once.
Two common slips
- Leaving out the brackets. A call is the name followed by
(). In Python, a line with onlygreetruns nothing and gives no error, so the program quietly skips the greeting. In Java,greet;will not compile. - Calling too early in Python. A call above the
defline stops the program with aNameError, becausegreetis not defined yet when that line runs.
Now try it yourself on the questions below.
Exercise 4.1.14.1.1 · Write itGreeting with a border
Write a program that reads a name and prints a greeting framed by two identical border lines.
- Read one name on a single line.
- Print
----------(ten hyphens) on the first line. - Print
Hello,followed by the name, then!on the second line. - Print
----------(ten hyphens) on the third line.
Define a function that prints the border line, and call it for both borders.
The name is always one word. Your program is run several times. Only what it prints is checked.
Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.
Examples
Your program is run 6 times: the 3 examples below, and 3 hidden ones that check the rules above. Only what it prints is checked.
a name with a border above and below (rules 2, 3, 4)
You type
- typed: Alice
It prints
---------- Hello, Alice! ----------
a different name (rule 3)
You type
- typed: Bob
It prints
---------- Hello, Bob! ----------
a single-character name (rule 3)
You type
- typed: X
It prints
---------- Hello, X! ----------
Exercise 4.1.24.1.2 · Answer itFunction purpose
(a) State one reason a programmer defines a function instead of writing the same code in two places. [1]
(b) State what happens when a program reaches a function definition (not a function call). [1]
[2]