Hackforge Academy

Category: python

Using global

Published on 27 Oct 2026

Explanation

global declares that assignment in a function targets a module-level name.

Code:

count = 0
def increment():
    global count
    count += 1
increment()
print(count)

Explanation

A name assigned inside a function is local by default; reading it before assignment can raise UnboundLocalError.

Code:

count = 10
def update():
    # print(count); count = 20  # UnboundLocalError
    pass
update()
print(count)

Explanation

nonlocal allows a nested function to reassign an existing variable in an enclosing function scope.

Code:

def outer():
    count = 0
    def inner():
        nonlocal count
        count += 1
    inner()
    print(count)
outer()

Explanation

global targets module scope; nonlocal targets an enclosing function scope.

Code:

value = 100
def outer():
    value = 10
    def inner():
        nonlocal value
        value += 5
    inner()
    print(value)
outer()

Explanation

A closure can preserve state between calls without using a global variable.

Code:

def counter_factory():
    count = 0
    def increment():
        nonlocal count
        count += 1
        return count
    return increment
c = counter_factory()
print(c(), c())

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community