Learn with diagrams, code, systems and practical examples.
Scope
Understand where names can be accessed and why local variables are useful.
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.
Small working example
Run this example first. Do not change several things at once; confirm the basic behavior, then experiment.
def greet():
message = "Hello"
return message
print(greet()) 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.
- Local names belong to their function scope.
- Explicit inputs and outputs improve design.
- Global state should be used carefully.
HelloThe example is intentionally small. Focus on the chapter’s main idea before adding extra syntax or framework code.
Common beginner mistake
Relying heavily on global variables that any function can modify.
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.
- Create two functions that use the same local variable name.
- Refactor a global value into a function parameter.