Return Values and Variable Scope · seed 1 · A4, ink-friendly. The answer key prints on its own page for grown-ups.

Return it, do not just show it

Computing · Programming · ages 15-16
Name ______________________   Date ____________
  1. What happens the moment a return runs?

    • The function restarts
    • The caller waits forever
    • The function ends on the spot
  2. What is a return value for?

    • Making code run faster
    • Letting later code use a computed result
    • Printing text on screen
  3. A function that prints shows output, while one that returns delivers a value.

    Circle one:   True   False

  4. In calcLineSlope, the return sits above the slope maths. What runs?

    • Everything above the return, then it exits
    • The whole function as normal
    • Only the line below the return
  5. calcScore returns correct out of 30 times 100. What does calcScore(27) hand back?

    Answer: ______________

  6. A total is made inside a function. What happens if later code outside tries to print it?

    • It prints the total as normal
    • It fails, since the name vanished with the call
    • It prints zero
  7. You need one score in three later sums. What is the right design?

    • Return the score and store it once for reuse
    • Print the score and retype it each time
    • Make the score global so anyone grabs it
  8. Where is the bug in calcLineSlope, and what is the fix?

    • The maths is wrong, so delete it
    • The parameters are wrong, so swap them
    • Return runs too early, so move it to the last line
LightMySky · lightmysky.comW1-mt_jivtTHpZc7-s1

Answer key

For grown-ups. Fold this page away before handing over the rest.

Return it, do not just show it W1-mt_jivtTHpZc7-s1

  1. The function ends on the spot · Nothing below a return ever runs.
  2. Letting later code use a computed result · A return hands a computed result to the caller for later use.
  3. True · Printing affects the screen, returning hands data to the caller.
  4. Everything above the return, then it exits · Nothing below a return ever runs, so the maths is dead code.
  5. 90 · 27 out of 30 is 0.9, and 0.9 times 100 is 90.
  6. It fails, since the name vanished with the call · Local names live inside their call and vanish after.
  7. Return the score and store it once for reuse · A stored return feeds every later use with no surprises.
  8. Return runs too early, so move it to the last line · An early return skips the maths. Returns belong last.
Worksheet · LightMySky