Skip to main content
Practice

Variable Scope and Nested Functions

In Python, where a variable is defined determines where it can be accessed. This is called scope.

Functions can also be nested, meaning one function can exist inside another.


1. Local vs Global Scope

Variables defined inside a function are local. They only exist while the function runs.

Variables defined outside any function are global and can be used throughout the script.

Local vs Global Scope
message = "Hello from global scope"

def show_message():
message = "Hello from local scope"
print(message)

show_message()
print(message)
  • Inside the function, a new message variable is created.
  • The global variable remains unchanged.

2. Using global Keyword

To modify a global variable inside a function, use the global keyword.

Using global Keyword
counter = 0

def increase():
global counter
counter += 1

increase()
print("Counter:", counter)
  • Without global, Python treats counter as a new local variable.
  • With global, it updates the variable outside the function.

3. Nested Functions

A function can be defined inside another function. The inner function is local to the outer one.

Nested Functions
def outer():
print("Outer function")

def inner():
print("Inner function")

inner()

outer()
  • inner() can only be called inside outer().
  • Nested functions help organize logic and encapsulate behavior.

Summary

ConceptDescription
Local ScopeVariables inside a function
Global ScopeVariables outside all functions
global keywordAllows modifying global variables inside functions
Nested FunctionsFunctions defined inside other functions

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.