Functions

Precap

A function is a named sequence of statements. Positional and keyword arguments can be defined to be used as input values. The return keyword can be used to return a result value.

Defining a function

The def keyword is used to define a function. In general a function consists of:

  • The def keyword

  • followed by an identifier as the function name

  • a pair of round brackets ()

  • within the round brackets an optional list of comma-separeted identifiers as positional or keyword arguments (both types of arguments can be used like variables)

  • a colon : after the round bracket

  • an indented list of statements

  • and optional return values using the return keyword.

Pseudo code of a function

NOTE: The pseudo code above will throw an error and syntax coloring also fails.

Calculating the surface and volume of a cuboid

Positional and keyword arguments

The difference between a positional and a keyword argument is, that the latter have a default value assigned to it and that.

Values for positional arguments

  • must be supplied when the function is called (i.e. if there are 3 positional arguments, 3 values have to be supplied)

  • in the order they are listed in the function definition

  • before any keyword arguments

whereas values for keyword arguments

  • can be supplied optionally when the function is called

  • and in any order if preceded by the keyword arguments identifier

  • after any positional arguments

Calculating the surface and volume of a cuboid

Variable scope

Positional and keyword arguments are variables with a limited outreach and lifespan.

Accessing a variable defined within a function from after the function has been called fails

Variables within a function definition have only local scope as long as they are not defined globally.

Accessing a variable defined within a function from after the function has been called fails

Excercise

Rewrite the code to use a function for the calculation to avoid repeating it