Skip to main content
Skip to main content

Visual to text coding
Lesson 12: Functions that give back

Years 5-6; 7-8

This is the final in a series of lessons to transition from visual coding to text-based coding with a General Purpose Programming language. See next steps for suggested courses and learning sequences after this lesson.

Included videos can be used by a beginner teacher and/or students to see how to code each of the simple programs step-by-step in all three languages: Scratch, Python and JavaScript.

This lesson may take two to three 45-minute periods. It builds on the coding concept of functions (see ACTDIP030 in Australian Curriculum: Digital Technologies – Digital Technologies Processes and Production Skills), by introducing the concept of return values. Functions are often written to return a result, which can then be used in the main program.


 


   
Next steps    


Learning hook

We can think of functions like tools that we delegate jobs to.

Here's how a toaster might look as a function:

What's missing from the table above?

The table only describes how to use the toaster. It doesn't give the code inside the function.

Modern toasters are actually very complicated! Most of us don't really know how to make one, but we generally don't need to. We just need to know how to use it. (See this video on Thomas Thwaites' quest to try to build a modern toaster from raw materials.)

As a class, see if you can complete the table for other tools:

In this lesson, we'll see how Python and JavaScript come with many built-in functions that we have already been using. These functions may have very complicated code inside, but luckily, we don't need to know it.

Then we'll look at the last concept we need to write our own functions – the return value.

Learning map and outcomes

In this lesson, students will:

  1. access an online programming environment for visual code (Scratch) and for General Purpose Programming (Python or JavaScript),
  2. identify and describe built-in functions already used,
  3. practise writing functions with return values,
  4. observe how functions are used in Graphical User Interfaces (GUIs), triggered by user inputs,
  5. write organised code for a small battle game by building a set of functions.

Learning input

Did you know you have been using built-in Python functions or JavaScript functions since the beginning of this course? Functions like print, alert or randint are all available because they were once written by someone else.

Work through these three examples to learn more about the functions you've been using.

Example 1

Consider this Python code:

print("Happy New Year!")

Identify and write down:

  • the name of the function being called,
  • the argument being supplied.


Example 2

Consider this JavaScript code:

alert("Welcome!");

Identify and write down:

  • the name of the function being called,
  • the argument being supplied,


Example 3

Just as parameters allow us to supply a function with values when we call it, functions can also return a value, to give back a result rather than just display it.

Consider this Python code:

dice_roll = randint(1, 6)

Identify and write down:

  • the name of the function being called,
  • the arguments being supplied,
  • the value returned by the function to be stored in dice_roll.


Example 4

Consider this JavaScript code:

playerName = prompt("What is your name?");

Identify and write down:

  • the name of the function being called,
  • the arguments being supplied,
  • the value returned by the function to be stored in playerName.

 

Learning construction

STEP 1: SETUP

For more on setting up and choosing a language, see Setting Up.

Unlike Lessons 10 and 11, this lesson does not use turtle graphics. The Python and JavaScript environments can be set up as in Lesson 1.

STEP 2: WRITING A FUNCTION TO RETURN A VALUE

The above video demonstrates a simple function that calculates the square of a given number, then returns the result. Try it yourself!


Solution code:

STEP 3: GETTING GOLD COINS

The video above shows a second example with a function that returns a random number between 2 and 20. Try it yourself!

(This is especially helpful for JavaScript! The messy code needed to get a random integer is now tidied away from the main program into a function.)

Solution code:

Next, let's say you're a bit more lucky than most. Change the code inside the function so that it always returns between 10 and 30 gold coins.

Finally, write a second function that returns a number of silver coins between 0 and 100. Add the call to your main program so that the silver coins are displayed after the gold coins.

Solution code:

STEP 4: A FUNCTION TO ANALYSE AN ARRAY

This final example shows a function that accepts an array, finds the lowest value in it, and returns that value. Try it yourself!

Solution code:

Next, add a second function to find the highest value in a given array. Test it with the same array from the main program.

Solution code:

STEP 5: FUNCTION EXERCISE

Carefully read the pseudocode below.

1   BEGIN
2     Function calculateFactorial(number)
3       result1
4       For i from 2 to number
5         resultresult × i
6       End For
7       Return result
8     EndFunction
9
10    factorial ← calculateFactorial(4)
11    Display 'The factorial of 4 is', factorial
12    Display 'The factorial of 5 is', calculateFactorial(5)
13  END

Predict the output of the program.

Now, implement the code in Python or JavaScript.

Mathematically, the factorial of 0 is always 1. Will the function work correctly if the argument for number is 0? Try it and see!

Solution code:

STEP 6: PREVIEW OF GRAPHICAL USER INTERFACES

So far, all our programs have relied on simple text input and output, sometimes called a Command Line Interface.

But both Python and JavaScript can be used to code applications with a Graphical User Interface (GUI) involving buttons, textboxes, images and other components. This is the kind of application we use everyday on webpages, phone or desktop apps, and functions are critical to making them work.

The final videos below preview JavaScript programs with GUIs.


Challenge

These challenges use the skills covered so far. By writing or modifying their own programs, students have an opportunity to demonstrate Application and Creation.

  1. Write and test a function that accepts a person's name, then returns a fancy greeting by choosing one of three random adjectives.

    For example, "Ladies and gentlemen, introducing the Illustrious Bob!"

    Here is the pseudocode for the function itself:

    Function produceWelcome(name)
        randomNumber ← choose random between 1 and 3
        If randomNumber = 1
            adjective ← 'Amazing'
        Else If randomNumber = 2
            adjective ← 'Illustrious'
        Else
            adjective ← 'Glorious'
        End If
        result = 'Ladies and gentlemen, introducing the', adjective, name, '!'
        Return result
    EndFunction
    

    In Python or JavaScript, implement the function and some test code in the main program.

Solution code:

  1. Develop a simple battle game with two functions.

    The function getOgreAttack() generates the amount of damage done every time the ogre attacks the player.

    • First, roll a 6-sided die. If the value is 2 or less, the troll misses and the damage is 0. Otherwise, roll two 6-sided dice and get the sum. This damage value is returned.

    TASK: Write the pseudocode for this function.

    TASK: Now code and test the function in Python or JavaScript.



Solution code:


  1. The function getPlayerAttack(lunge) is called every time the player takes a swing at the ogre. It calculates and returns the damage value by the following process:

    • If lunge is False, this is a normal attack. First, roll an 8-sided die. If the value is 2 or less, the player misses and the damage is 0. If the value is 8, this is a critical hit and the damage is 20. Otherwise, roll three 5-sided dice and get the sum.
    • If lunge is True, this is a lunge attack. First, roll an 8-sided die. If the value is 3 or less, the player misses and the damage is 0. Otherwise, roll three 10-sided dice and get the sum.

    TASK: Write the pseudocode for this function.

    TASK: Now code and test the function in Python or JavaScript.



Solution code:

  1. The main program keeps track of the player's health (start with 40) and ogre's health (start with 60).

    It contains a loop for the game, with the following steps inside:

    • The ogre goes first. Get the ogre's damage using the function you made, then subtract it from the player's health. Display as "The ogre hits you for ?? damage."
    • If the player is still alive, ask the player whether to lunge or not, then get the player's damage using the function you made and subtract it from the ogre's health. Display as "You hit the ogre for ?? damage."
    • Display current health of player and ogre.

    The loop ends if the player's health or the ogre's health reaches 0 or below.

  2. TASK: Write the pseudocode for the main program.

    TASK: Finally, code and test the main program along with the functions you already coded.

Solution code:

Next steps

Congratulations on working through the 12 lessons in this series.

Click here for suggestions for continuing the journey with JavaScript or Python.

Resources

  • Setting up online environments
  • Online environments for coding in each language
    • Scratch
    • repl.it: an online environment suited to Python
    • JSFiddle: an online environment suited to JavaScript
  • Cheat sheets listing basic commands for coding:
    • Python Cheatsheet (from Grok Learning)
    • JavaScript CheatSheet (Tip: Press the little blue tabs to move Variables, Basics, Strings and Data Types to the top.)