HOLIDAY SALE! Save 50% on Membership with code HOLIDAY50. Save 15% on Mentorship with code HOLIDAY15.

4) Functions and Scope Lesson

Python Local Function Scope

4 min to complete · By Martin Breuss

In the previous lessons, you've written a function, greet(), and used docstrings and type hints to better describe it. You've also learned that you need to return a value if you want to use it outside of your function scope.

In this lesson, you'll look closer at what scopes are and how they apply to functions. Your greet() function contains three variables:

  1. greeting
  2. name
  3. sentence

greeting and name are two parameters that get filled with the value of the arguments a user passes when calling your function. sentence gets created within the body of your function.

In this lesson, you'll start to learn about scope, which influences where you have access to the values of these variables.

Python Local Function Scope

Function-internal variables live only inside the function. You can refer to the function parameters inside your function as much as you want to, but you won't be able to access them outside of it:

def greet(greeting: str, name: str) -> str:
    """Generates a greeting"""
    sentence = f"{greeting}, {name}! How are you?"
    return sentence

print(name)  
# OUTPUT: NameError: name 'name' is not defined

Trying to print the function-internal variable name outside of the function body will throw a NameError. Python doesn't have anything assigned to the variable name in the global scope of your script. The same is true for any other variable in your function, whether you received it as a parameter, such as greeting and name, or you defined it inside the function, such as sentence:

def greet(greeting: str, name: str) -> str:
    """Generates a greeting"""
    sentence = f"{greeting}, {name}! How are you?"
    return sentence

print(sentence)  
# OUTPUT: NameError: name 'sentence' is not defined

Function-internal variables can't be re-used outside of the function's scope. To re-use any value generated in the function, you need to squeeze it through the return statement and expose it to your global scope.

Colorful illustration of a light bulb

Info: Even though you are returning the value of your function-internal sentence variable, that doesn't make the variable accessible in your global scope. All you do is expose the value of that variable, and you'll need to assign it to a new variable in the global scope.

In the next lesson, you'll dive deeper into the concept of scopes and walk through a step-by-step example to better understand how they work.

Summary: What is Python Scope

  • Variables inside a function body aren't accessible outside of your function. They only exist in the local function scope.