1.2.1.2 PCEP-30-02 Practice Test Compendium – Functions

Functions – continued

10) A function definition can declare default values for some or all of its parameters. When the invocation does not provide arguments for these parameters, the default values are taken into consideration. Note: parameters with default values must not precede the ones without them. For example, the following snippet prints 1 2 3 to the screen:

def function(a, b, c):
    print(a, b, c)


function(1, c=3, b=2)

11) Note that the following invocation is incorrect and will raise the TypeError exception, because the a parameter is set twice (once with the positional passing and once with the keyword passing) while the c parameter is not set at all.

function(1, a=1, b=2)

12) A scope is the part of the code where a certain name is properly recognizable.

13) A variable existing outside a function has a scope which includes the function's bodies.

14) A variable defined inside the function has a scope inside the function's body only.

15) If a certain variable is used inside a function and the variable’s name is listed as an argument of the global keyword, it has global scope, and it is also recognizable outside the function. For example, the following snippet outputs 2 to the screen:

def function():
    global variable
    variable += 1


variable = 1
function()
print(variable)

Note: removing the line containing the global keyword will spoil the code and the UnboundLocalError exception will be raised.

16) Changing the parameter's value doesn't propagate it outside the function. For example, the following snippet outputs [1] to the screen:

def function(parameter):
    parameter = [2]


the_list = [1]
function(the_list)
print(the_list)

17) If the parameter is a list or a dictionary, changing its contents propagates them outside the function. For example, the following snippet outputs [2] to the screen:

def function(parameter):
    parameter[0] = 2


the_list = [1]
function(the_list)
print(the_list)

18) Recursion is a programming technique in which the function invokes itself to perform a complex task. For example, the following snippet contains a function that evaluates the factorial of its argument and prints 120 to the screen:

def factorial(n):
    if n < 2:
        return n
    else:
        return n * factorial(n - 1)


print(factorial(5))

Last updated