Skip to content
ExamSpine

Lesson 4.2

Pass a value in

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.

Pass a value in

By the end of this you will be able to give a function a value when you call it, call the same function with different values, and use that value inside the function through its own name.

The functions in the last lesson did the same thing on every call. Most jobs need a detail that changes: which word to print, how many times, how wide. A parameter is a name in the brackets of the definition. Each call puts a value in the brackets, and for that call the parameter holds that value.

One function, different values

A cafe prints a label for each item on its counter.

def label(item):
    print("[ " + item + " ]")

label("tea")
label("milk")
public static void main(String[] args) {
    label("tea");
    label("milk");
}

static void label(String item) {
    System.out.println("[ " + item + " ]");
}

This prints [ tea ], then [ milk ]. In the first call, item holds "tea" while the body runs. In the second call, item holds "milk". The body is written once, and the value in the call decides what it prints.

In Python, the parameter is just a name. In Java, each parameter has a type in front of it, here String item, and a call must give a value of that type. The value written in a call is called an argument.

A value from input, under a new name

The argument does not have to be written into the program. It can be a variable holding something the user typed. This program counts down from a number the user types.

def countdown(n):
    while n > 0:
        print(n)
        n = n - 1
    print("Go!")

seconds = int(input())
countdown(seconds)
print("Started from " + str(seconds))
import java.util.Scanner;

public static void main(String[] args) {
    Scanner scanner
        = new Scanner(System.in);
    int seconds = Integer.parseInt(
        scanner.nextLine());
    countdown(seconds);
    System.out.println(
        "Started from " + seconds);
}

static void countdown(int n) {
    while (n > 0) {
        System.out.println(n);
        n = n - 1;
    }
    System.out.println("Go!");
}

If the user types 3, the call countdown(seconds) hands the value 3 to the function, so n starts at 3. Here is the loop inside the function.

ChecknIs n > 0?Printed after the check
13Yes3
22Yes2
31Yes1
40Nonothing: the loop ends

After the loop, the function prints Go!, and the program carries on after the call with Started from 3.

Two things to notice. The variable in the call is called seconds and the parameter is called n: the names do not have to match, because the call hands over a value, not a name. And the function counted n down to 0, yet seconds is still 3 afterwards. The parameter is the function's own name for the value, and giving it a new value inside the function does not change the variable that was passed in.

Two values in

A function can take more than one parameter, separated by commas. The values in the call are matched to the parameters in order: the first value goes to the first parameter, the second to the second.

def price_tag(item, price):
    print(item + " costs " + str(price))

price_tag("tea", 3)
price_tag("cake", 5)
public static void main(String[] args) {
    priceTag("tea", 3);
    priceTag("cake", 5);
}

static void priceTag(String item, int price) {
    System.out.println(
        item + " costs " + price);
}

This prints tea costs 3, then cake costs 5. Swap the two values in a call and they land in the wrong parameters: price gets the text and item gets the number. Here that is an error. In Python, the program stops when that line runs, because a number cannot be joined to text with +. In Java, the program will not compile, because the types do not match.

Two common slips

  • The wrong number of values. A call gives one value for each parameter. Calling label() with nothing in the brackets is an error in both languages.
  • Ignoring the parameter. A function that prints a fixed text, instead of using its parameter, prints the same thing whatever value it was given. Inside the function, reach the value through the parameter's name.

Now try it yourself on the questions below.

Exercise 4.2.14.2.1 · Write itShow N times

Write a program that reads a line of text and a number, then prints that text exactly that many times.

  1. Read the text on the first line.
  2. Read the count (whole number) on the second line.
  3. Print the text on its own line, repeated exactly count times (one copy per line).

Define a function that takes the text and the count. The count is a whole number from 1 to 100. 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.

  • three copies of hello (rule 3)

    You type

    1. typed: hello
    2. typed: 3

    It prints

    hello
    hello
    hello
  • one copy (rule 3)

    You type

    1. typed: test
    2. typed: 1

    It prints

    test
  • four copies (rule 3)

    You type

    1. typed: go
    2. typed: 4

    It prints

    go
    go
    go
    go
solution.pySolution.java

Exercise 4.2.24.2.2 · Write itCustom border

Write a program that reads a border character, a width, and a message, then prints the message between two border lines.

  1. Read the border character (one character) on the first line.
  2. Read the width (whole number) on the second line.
  3. Read the message (text) on the third line.
  4. Print a line of the border character repeated exactly width times.
  5. Print the message.
  6. Print the same border line again.

Define a function that takes the character and width and prints one border line. Call it for both borders.

The width is a whole number from 1 to 50. 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.

  • 5 stars above and below Hello (rules 4, 5, 6)

    You type

    1. typed: *
    2. typed: 5
    3. typed: Hello

    It prints

    *****
    Hello
    *****
  • 8 hyphens as borders (rule 4)

    You type

    1. typed: -
    2. typed: 8
    3. typed: Test

    It prints

    --------
    Test
    --------
  • 3 hash characters (rule 4)

    You type

    1. typed: #
    2. typed: 3
    3. typed: Go

    It prints

    ###
    Go
    ###
solution.pySolution.java