Technology Scope | Python Tutorial

Learn with diagrams, code, systems and practical examples.

</>
TutorialsPythonScope
Functions & Modules · Chapter 16

Scope

Understand where names can be accessed and why local variables are useful.

Why this matters

Scope prevents every variable in a program from interfering with every other variable.

Start with the idea

Names created inside a function are normally local to that function. Code outside cannot directly use those local names unless a value is returned or otherwise shared intentionally.

IdeaUnderstand the purpose
CodeRun the smallest example
PracticeChange it yourself
SubjectVision learning pattern: understand the idea before memorizing syntax.

Small working example

Run this example first. Do not change several things at once; confirm the basic behavior, then experiment.

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

print(greet())
Expected output
Hello
What to notice

The example is intentionally small. Focus on the chapter’s main idea before adding extra syntax or framework code.

Common beginner mistake

Mistake

Relying heavily on global variables that any function can modify.

Better approach

Prefer parameters and return values so data flow is visible and testable.

Quick recap

  • Local names belong to their function scope.
  • Explicit inputs and outputs improve design.
  • Global state should be used carefully.

Try it yourself

These are deliberately small. If you can complete them without copying the example, you are ready to continue.

  1. Create two functions that use the same local variable name.
  2. Refactor a global value into a function parameter.