Python Scope

Scope determines where a variable can be accessed in a program. Variables created inside a function belong to the local scope, while variables created outside a function belong to the global scope. Local Scope A variable created inside a function can only be used inside that function. Example Output: Local Variable Cannot Be Accessed Outside […]

2 mins read Lesson 43 of 56 77% through track

Scope determines where a variable can be accessed in a program. Variables created inside a function belong to the local scope, while variables created outside a function belong to the global scope.

Local Scope

A variable created inside a function can only be used inside that function.

Example

def greet():
    message = "Hello Python"
    print(message)

greet()

Output:

Hello Python

Local Variable Cannot Be Accessed Outside

Example

def greet():
    message = "Hello Python"

greet()

print(message)

Output:

NameError: name 'message' is not defined

Global Scope

A variable created outside a function can be accessed anywhere in the program.

Example

message = "Welcome"

def greet():
    print(message)

greet()

Output:

Welcome

Local and Global Variables with Same Name

A local variable takes priority inside the function.

Example

name = "John"

def show_name():
    name = "Alice"
    print(name)

show_name()
print(name)

Output:

Alice
John

Using the global Keyword

The global keyword allows you to modify a global variable inside a function.

Example

count = 0

def increase():
    global count
    count += 1

increase()

print(count)

Output:

1

Creating a Global Variable Inside a Function

Example

def create_variable():
    global message
    message = "Python"

create_variable()

print(message)

Output:

Python

Nested Function Scope

Variables in an outer function can be accessed by an inner function.

Example

def outer():
    message = "Hello"

    def inner():
        print(message)

    inner()

outer()

Output:

Hello

Summary

  • Scope defines where a variable can be accessed.
  • Variables inside a function have local scope.
  • Variables outside a function have global scope.
  • Local variables cannot be accessed outside their function.
  • Global variables can be accessed throughout the program.
  • The global keyword is used to modify global variables inside functions.
  • Nested functions can access variables from their outer functions.