w3resource

What is scope in Python functions? Explain with an example.

Understanding Python function scope: Local, global, and nested scopes

In Python, scope refers to the visibility and accessibility of variables within different parts of a program. Scope determines where a variable is accessible and where not. In order to understand how variables behave within functions and how they interact with each other, it is crucial to understand scope.

Python has two main types of scope:

Local scope:

  • Variables declared within a function have local scope. They are accessible only within the function in which they are defined.
  • Local variables are created when the function is called and destroyed when it exits.
  • Local variables cannot be accessed from outside the function.

Example: Local scope

def add_numbers(x, y):
    result = x + y
    print(result)

add_numbers(4, 7)  # Output: 11
print(result)  # NameError: name 'result' is not defined

Global Scope:

Variables declared outside of any function or at the top level of a script have global scope. They are accessible throughout the program.

During program startup, global variables are created in memory and remain there until the program ends.

Global variables can be accessed from any function within the program.

Example: Global scope:

greeting = "Hello"  # Global variable
def message():
    print(greeting)
message()  # Output: Hello
print(greeting)  # Output: Hello

Nested scope:

  • Python allows nested functions, where one function is defined inside another.
  • During nested functions, the inner function has access to variables in the outer (enclosed) function.
  • The inner function's scope is called "nested scope" because it includes both its local scope and the enclosing function's scope.

Example: Nested scope

def outside_function():
    outer_variable = "This is from outside function."

    def inside_function():
        inner_variable = "This is from inside function."
        print(outer_variable)  # Accessing outer function's variable
        print(inner_variable)

    inside_function()

outside_function()
# Output:
# This is from outside function.
# This is from inside function.


Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-interview/what-is-scope-in-python-functions.php