Chapter 6: Function scope

When one shares the same name

face Josiah Wang

What happens when you have the same variable names in different functions?

What do you think the output is when you run the code below? Try running the code to confirm your answer.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
def negate(number):
    number = -number
    print(f"Inside negate: {number}")
    return number

def absolute_value(number):
    threshold = 0
    print(f"Inside absolute value: {number}")
    if number < threshold:
        return negate(number)
    return number

number = 9
result = absolute_value(-5)
print(f"Outside: {number}")

If you have run the code (you did run it, didn’t you? 🥺), the output should be:

Inside absolute value: -5
Inside negate: 5
Outside: 9

So it looks like each function will keep its own variable number. So the variable number defined in Line 1 is different from the variable number defined in Line 6, and they are both different from the variable number in Line 13. You can imagine that these are three different individuals, they just all happen to share the same name.

Same name