HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to Python: Print and RepeatVariablesData Types & NumbersStringsListsConditions (if / elif / else)Loops (for / while)FunctionsOperatorsDictionariesTuples & SetsError Handling (try / except)Classes (Object-Oriented)File OperationsComments & IndentationBooleans (True / False)Lambda & map / filterModules (import)InheritanceVariable Scope
REFERENCE
📖 Overview
🖥️ Output & Input
🔢 Numbers & Math
✍️ String
📋 List
🗂️ Dictionary & Set
🔁 Condition & Loop
🧩 Function
📁 File & Error
🔄 Type & Conversion
Python›Variable Scope

Variable Scope

Variables inside (local) and outside (global) a function; the global keyword.

Simple enough for a 5-year-old to understand

Local vs global

A variable defined INSIDE a function lives only there (local). One defined outside is visible everywhere (global).

Example code
1
message = "outside"
A global variable.
VariableA global variable.
2
def write():
A function.
FunctionA function.
3
print(message)
Can read global: outside
Output / InputCan read global: outside
4
write()
Call → prints outside.
FunctionCall → prints outside.
VariableFunctionOutput / Input
💡 Hint: A variable created inside a function is NOT visible from outside; it lives only in that function.

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.Can a variable created inside a function be accessed from outside?

About this topic

Scope is where a variable is visible. A variable you define inside a function lives only inside that function; it disappears when the function ends. This isn't a restriction, but a protection: functions cannot accidentally corrupt each other's variables.

When searching for a name, Python follows a specific order: it first looks inside the function itself, then in the enclosing function, then at the module level, and finally at built-in names. Knowing this order clarifies the answers to "why can't I see this variable" or "why isn't the change visible outside".

What you will learn

  • The distinction between local and global scope
  • Allowing a function to read an outer variable but not modify it
  • The global and nonlocal keywords
  • The scope chain in nested functions
  • Why using global variables is discouraged

When to use?

Scope knowledge is most useful when debugging: if a change you made in a function isn't visible outside or you can't access the expected variable, the problem is almost always scope.

In practice, the right approach is for functions to take the data they need as PARAMETERS and return the result with RETURN. Moving data via global variables makes it impossible to track at what point the program changes what.

Common mistakes

Wrong

count = 0

def increase():
    count = count + 1

increase()

When you make an assignment to a name inside a function, Python treats it as a local variable; since it doesn't have a value on the right-hand side yet, it throws the error "UnboundLocalError: cannot access local variable 'count' where it is not associated with a value".

Correct

count = 0

def increase(current):
    return current + 1

count = increase(count)

Wrong

def setup():
    config = {"debug": True}

setup()
print(config)

Because config is defined inside the function, it disappears when the function ends; trying to access it from the outside gives "NameError: name 'config' is not defined". The correct way to carry the value outside is to return it.

Correct

def setup():
    return {"debug": True}

config = setup()
print(config)

Wrong

total = 0

def add(n):
    global total
    total += n

Technically it works, but it's poor design: since it changes the state outside the function, it can produce different results for the same input and makes testing difficult. Global state is one of the most error-prone patterns in growing projects.

Correct

def add(total, n):
    return total + n

total = 0
total = add(total, 5)

Frequently asked questions

Can a function read an outer variable?

Yes, it can read it. The problem starts when you try to write to it: the moment you make an assignment, Python considers that name local and breaks the connection with the external variable. This asymmetry is the most confusing behavior regarding scope.

What is the difference between global and nonlocal?

global allows writing to the file-level variable. nonlocal, on the other hand, allows writing to the variable of the immediate outer function in nested functions. Both should be considered a last resort; in most cases, the same job is done much cleaner with parameters and return.

Does the loop variable exist even after the loop?

Yes, in Python, the for loop's variable remains accessible even after the loop finishes and holds its last value. This is not the case in many languages; if you don't know this difference, you might read an unexpected value after the loop.

Summary

Scope is where a name is visible; variables inside a function cannot be accessed from outside. A function can read an outer variable, but the moment it makes an assignment, it treats it as local — UnboundLocalError is the sign of this. The correct way is to take parameters and return results.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code