Function Scope (Local and Global Variables)

  • Learn how local and global variables work inside Python functions.

  • What is Scope in Python?

    Scope refers to the area of a program where a variable can be accessed.

    👉 It decides:

    • Where a variable is created

    • Where it can be used

    • Where it cannot be accessed

    Why is Scope Important?

    Scope helps to:

    •  Avoid variable name conflicts

    • Improve program security

    • Manage memory efficiently

    • Make code easier to understand

    • Control data access

    Types of Scope in Python

    Python mainly has two types of scope for beginners:

    1. Local Scope

    2. Global Scope

    1.Local Scope

    What is a Local Variable?

    A local variable is a variable defined inside a function.

    👉 It can be accessed only inside that function.

    Syntax

    def function_name():

        variable = value   # local variable

Local Variable Inside Function

This variable is created inside the function and cannot be accessed outside.

def show():
    message = "Hello Python"   # local variable
    print(message)

show()
  • Accessing Local Variable Outside Function

    print(message)   # Error: message is not defined

    Key Points of Local Scope

    •  Created inside a function

    • Exists only during function execution

    • Destroyed after function ends

    •  Cannot be accessed outside

    2.Global Scope

    What is a Global Variable?

    A global variable is a variable defined outside all functions.

    👉 It can be accessed anywhere in the program.

    Syntax

    variable = value   # global variable


    def function_name():

        print(variable)

Using Global Variable Inside Function

This function accesses a global variable defined outside.

name = "Python"   # global variable
def show():
    print(name)

show()
  • Key Points of Global Scope

    •  Defined outside functions

    • Accessible inside and outside functions

    • Exists throughout program execution

Local vs Global Variable with Same Name

This example shows that local variable has higher priority inside function.

x = 10   # global variable

def test():
    x = 5   # local variable
    print("Inside function:", x)

test()
print("Outside function:", x)
  • Using global Keyword

    Why Use global Keyword?

    If you want to modify a global variable inside a function, you must use the global keyword.

    Syntax

    global variable_name

Using global Keyword

This program modifies a global variable inside a function.

count = 0   # global variable

def increase():
    global count
    count += 1

increase()
print(count)

⚠️ Without global Keyword (Error Example)

count = 0

def increase():
    count += 1   # Error: local variable referenced before assignment