Skip to content
ExamSpine

Lesson 4.3

Return a value

Part 4: FunctionsReading, about 6 min3 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.

Return a value

By the end of this you will be able to write a function that hands a value back to the code that called it, use that value, and say why a function stops at its first return.

The functions so far did their job by printing. Often the code that calls a function wants the answer itself, to store it, to work with it, or to print it later. A return statement sends a value back to the caller. The call then stands for that value, as if the value had been written where the call is.

Return sends a value back

def shout(word):
    return word + "!"

loud = shout("hello")
print(loud)
public static void main(String[] args) {
    String loud = shout("hello");
    System.out.println(loud);
}

static String shout(String word) {
    return word + "!";
}

The call shout("hello") runs the body with word holding "hello". The body works out "hello!" and returns it. Back in the main code, the call is replaced by that value, so loud holds "hello!", and the next line prints hello!. The function itself prints nothing.

In Java, the type written just before the method's name is its return type: the type of the value it sends back. shout returns text, so its return type is String. A method that returns a whole number has int there, and one that returns true or false has boolean. The word void means the method returns nothing, which is why the methods in the last two lessons had it. In Python, the def line says nothing about what comes back: only the return inside shows it.

Using the value that comes back

A call that returns a value can go anywhere that value could go. Here are two more uses of the same shout function.

def shout(word):
    return word + "!"

print(shout("stop") + " Now.")
print(shout(shout("hey")))
public static void main(String[] args) {
    System.out.println(
        shout("stop") + " Now.");
    System.out.println(shout(shout("hey")));
}

static String shout(String word) {
    return word + "!";
}

The first print joins the returned "stop!" to more text and prints stop! Now.. In the second print, the inner call runs first and returns "hey!". That value is the argument of the outer call, which returns "hey!!", and hey!! is printed.

Printing is not returning

Here is a function that prints its answer instead of returning it.

def shout_print(word):
    print(word + "!")
static void shoutPrint(String word) {
    System.out.println(word + "!");
}

Calling it shows hello! on the screen, but nothing comes back for the caller to use. In Python, a function that finishes without reaching a return sends back the special value None, so after result = shout_print("hello"), the variable result holds None, and printing it shows None. In Java, the method is void, so a line such as String result = shoutPrint("hello"); does not compile: there is no value to store.

So the rule is simple. If the caller needs the answer, return it. Print it only when showing it is the whole job.

Return ends the function

A return does two things: it sends the value back, and it ends the function at once. Nothing after it in the function runs on that call, not even the rest of a loop. This function finds the smallest number above 1 that divides n with no remainder, for a whole number n of 2 or more.

def smallest_factor(n):
    for d in range(2, n):
        if n % d == 0:
            return d
    return n
static int smallestFactor(int n) {
    for (int d = 2; d < n; d++) {
        if (n % d == 0) {
            return d;
        }
    }
    return n;
}

Here is the call smallest_factor(15) (in Java, smallestFactor(15)).

dn % dIs it 0?What happens
21Nothe loop goes on
30Yesreturn 3: the function ends

The loop never reaches 4, and the last line, return n, does not run on this call. Now try n as 7. No value of d from 2 to 6 divides 7, so the loop runs to the end without returning, and the last line returns 7.

Two common slips

  • Forgetting the return. In Python, a function that works out an answer but never returns it gives back None. In Java, a method with a return type must return a value of that type: if the compiler finds a way through the method that reaches its end without a return, the method does not compile ("missing return statement").
  • Writing a line just after a return, at the same level, as if it will still run. It never can. In Python it is skipped. In Java it does not compile ("unreachable statement").

Now try it yourself on the questions below.

Exercise 4.3.14.3.1 · Write itDouble a number

Write a function that returns twice the value of its input.

  1. n is a whole number from -1000 to 1000.
  2. Return n multiplied by 2.

Only the number your function returns is checked.

def double_value(n: int) -> int

Examples

Your function is tested on 6 cases: the 3 examples below, and 3 hidden ones that check the rules above.

  • double_value(3) should return 6: a small positive number (rule 2)
  • double_value(0) should return 0: zero doubled is zero (rule 2)
  • double_value(-4) should return -8: a negative number (rule 2)

public static int doubleValue(int n)

Checking whether Java answers can run here.

Examples

Your function is tested on 6 cases: the 3 examples below, and 3 hidden ones that check the rules above.

  • doubleValue(3) should return 6: a small positive number (rule 2)
  • doubleValue(0) should return 0: zero doubled is zero (rule 2)
  • doubleValue(-4) should return -8: a negative number (rule 2)
solution.pySolution.java

Exercise 4.3.24.3.2 · Write itAbsolute value

Write a function that returns the absolute value of a whole number (its distance from zero, always zero or positive).

  1. n is a whole number from -1000 to 1000: it can be negative, zero, or positive.
  2. If n is negative, return its positive version.
  3. If n is zero or positive, return it unchanged.
  4. Do not use any built-in absolute-value function.

Only the number your function returns is checked.

def absolute_value(n: int) -> int

You cannot use these in this question:

  • abs()

This question is about writing the logic yourself, so built-in absolute-value functions are not allowed.

Examples

Your function is tested on 6 cases: the 3 examples below, and 3 hidden ones that check the rules above.

  • absolute_value(-5) should return 5: a negative number becomes positive (rule 2)
  • absolute_value(3) should return 3: a positive number stays the same (rule 3)
  • absolute_value(0) should return 0: zero stays zero (rule 3)

public static int absoluteValue(int n)

Checking whether Java answers can run here.

You cannot use these in this question:

  • Math.abs()

This question is about writing the logic yourself, so built-in absolute-value functions are not allowed.

Examples

Your function is tested on 6 cases: the 3 examples below, and 3 hidden ones that check the rules above.

  • absoluteValue(-5) should return 5: a negative number becomes positive (rule 2)
  • absoluteValue(3) should return 3: a positive number stays the same (rule 3)
  • absoluteValue(0) should return 0: zero stays zero (rule 3)
solution.pySolution.java

Exercise 4.3.34.3.3 · Write itIs even

Write a function that returns whether a whole number is even.

  1. n is a whole number that can be negative, zero, or positive.
  2. Return True (Python) or true (Java) if n is divisible by 2 with no remainder, False or false otherwise.
  3. Zero is even.

Only the value your function returns is checked.

def is_even(n: int) -> bool

Examples

Your function is tested on 7 cases: the 3 examples below, and 4 hidden ones that check the rules above.

  • is_even(4) should return True: a positive even number (rule 2)
  • is_even(7) should return False: an odd number (rule 2)
  • is_even(0) should return True: zero is even (rule 3)

public static boolean isEven(int n)

Checking whether Java answers can run here.

Examples

Your function is tested on 7 cases: the 3 examples below, and 4 hidden ones that check the rules above.

  • isEven(4) should return true: a positive even number (rule 2)
  • isEven(7) should return false: an odd number (rule 2)
  • isEven(0) should return true: zero is even (rule 3)
solution.pySolution.java