Functions, parameters and scope

Defining and calling a function, passing it arguments, getting its return value, and knowing where a variable exists: local, global, shadowed.

  • 28 cards
  • 6 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Scenarios
  5. Understand
  6. Line by line

A few cards from the deck

  • Function: what is it?

    Show the answer

    A named block of statements, called as many times as needed with different data, which returns a result.

    You define it once with def, then call it by its name followed by parentheses: area(3).

  • What does this program print?

    ```python
    def double(x):
    print(x * 2)

    r = double(4)
    print(r)
    `

    • 8 then None
    • 8 then 8
    • 8 only
    • None only
    Show the answer

    8 then None

    The call prints 8, but the function has no return: it returns None, which r receives. Printing a value is not returning it.

  • A … is a subprogram that acts (printing, saving) without returning a result; in Python, calling it gives ….

    Show the answer

    A procedure is a subprogram that acts (printing, saving) without returning a result; in Python, calling it gives None.

    Python's syntax does not tell the two apart: a procedure is a function with no return, or whose return gives nothing back.

  • Formal parameter: what is it?

    Show the answer

    A name written in a function's header, which receives a value at each call: radius in def area(radius):.

    It is a local variable of the function, initialised by the call.