Chapter 6: Function scope

Check your understanding of scopes

face Josiah Wang

Was that clear? Or confusing?

Take a guess at answering the quiz below, to see whether you actually understood correctly what we discussed earlier.

1 2 3 4

Question 1

What is the output of the following program? Enter "Error" if you predict an error to occur.

1
2
3
4
5
6
7
8
def absolute_value(number):
    print(y)
    if number < 0:
        return -number
    return number

y = 10
result = absolute_value(5)
10
Explanation:

Although y is not defined locally, it is defined in the global scope.

Question 2

What is the output of the following program? Enter "Error" if you predict an error to occur.

1
2
3
4
5
6
7
8
9
y = 10

def absolute_value(number):
    print(y)
    if number < 0:
        return -number
    return number

result = absolute_value(5)
10
Explanation:

The variable y is defined in the global scope.

Question 3

What is the output of the following program? Enter "Error" if you predict an error to occur.

1
2
3
4
5
6
7
8
def absolute_value(number):
    print(y)
    if number < 0:
        return -number
    return number

result = absolute_value(5)
y = 10
Error
Explanation:

The variable y is not yet defined in the global scope when Line 7 is executed. It is only defined in Line 8.

Question 4

What is the output of the following program? Enter "Error" if you predict an error to occur.

1
2
3
4
5
6
7
8
9
def absolute_value(number):
    y = y + 2
    print(y)
    if number < 0:
        return -number
    return number

y = 10
result = absolute_value(5)
Error
Explanation:

In Line 2, Python assumes that y will be a local variable, but then struggled with y + 2 since y is not yet defined! To get this working, you need to add global y in between Lines 1 and 2 to force Python to use the y from the global namespace. Be careful though - this can cause undesired side effects! The function can freely modify the value of y, and any changes will persist even after the function returns. It will be hard to trace any changes to y if you allow anybody to modify y. The use of such global variables is generally discouraged - try to keep all variables local when possible!