Skip to content
Computing · Year 9 · Advanced Programming with Python · Autumn Term

Scope of Variables (Local vs. Global)

Students will understand the concept of variable scope within functions and the main program.

National Curriculum Attainment TargetsKS3: Computing - Programming and Development

About This Topic

Variable scope defines the regions of a program where a variable is accessible. In Python, local variables declared inside functions exist only within that function and its nested blocks, while global variables defined at the top level remain available throughout the entire script. Year 9 students grasp this by creating simple programs that use both types, predicting outputs when a local variable shares a name with a global one, and examining how this shadowing hides the global value inside the function.

This concept supports KS3 Computing standards in programming by building modular thinking. Students learn that overusing global variables creates tight coupling between functions, making code harder to debug and reuse. Instead, passing arguments and returning values encourages function independence, a key step toward professional software practices.

Hands-on coding activities make scope tangible. Students run predictions against actual outputs, spot errors in peer code, and refactor globals to locals, reinforcing rules through trial and error. Active learning excels here because immediate feedback from interpreters clarifies abstract boundaries, boosting confidence in complex programs.

Key Questions

  1. Explain the difference between local and global variables in a Python program.
  2. Predict the output of a program that uses both local and global variables with the same name.
  3. Analyze the potential pitfalls of overusing global variables in modular programming.

Learning Objectives

  • Compare the execution flow and accessibility of variables within functions versus the main program body.
  • Predict the output of Python programs where local and global variables share the same identifier.
  • Analyze the impact of variable scope on code readability and maintainability in modular programs.
  • Design Python functions that effectively use local variables to avoid unintended side effects.
  • Evaluate the trade-offs between using global variables and passing parameters for data sharing between functions.

Before You Start

Introduction to Functions in Python

Why: Students need to understand what functions are and how they are defined before learning about variables local to them.

Basic Python Syntax and Data Types

Why: Students must be familiar with how to declare and assign values to variables to understand scope.

Key Vocabulary

ScopeThe region within a program where a variable is recognized and can be accessed. It determines the variable's lifetime and visibility.
Local VariableA variable declared inside a function. It is only accessible within that specific function and is destroyed when the function finishes executing.
Global VariableA variable declared outside of any function, at the top level of the script. It is accessible from anywhere in the program, both inside and outside functions.
Variable ShadowingWhen a local variable has the same name as a global variable. Inside the function, the local variable takes precedence, hiding the global variable.

Watch Out for These Misconceptions

Common MisconceptionAll variables created in a program are global and accessible everywhere.

What to Teach Instead

Local variables vanish after the function ends, preventing accidental changes elsewhere. Pair prediction activities help students run tests showing 'NameError' outside functions, building accurate mental models through evidence.

Common MisconceptionA local variable with the same name as a global permanently changes the global.

What to Teach Instead

Shadowing creates a separate local copy; the global stays unchanged. Debug relays let groups observe this via print statements before/after calls, correcting the belief via direct experimentation.

Common MisconceptionFunctions always need 'global' keyword to read globals.

What to Teach Instead

Reading globals works without it, but assignment requires 'global'. Live demos clarify this distinction, as students vote and verify behaviors in real-time.

Active Learning Ideas

See all activities

Real-World Connections

  • Software developers building complex applications, like the operating system for a smartphone, use variable scope to manage millions of lines of code. They ensure that settings specific to one app, such as a game's high score, do not accidentally affect another app, like the camera's focus settings.
  • Game designers use variable scope to control game elements. For example, a variable tracking the player's health might be global, accessible everywhere, while a variable for temporary power-up duration would be local to the power-up's activation function, disappearing after the power-up expires.

Assessment Ideas

Quick Check

Present students with a short Python code snippet containing both local and global variables, some with identical names. Ask them to write down the predicted output and circle the variables they identify as global and underline those they identify as local.

Discussion Prompt

Pose the question: 'Imagine you are building a program with 10 functions. What are the risks of declaring all variables as global? How could you make the program more robust by using local variables instead?' Facilitate a class discussion on the pros and cons.

Exit Ticket

Ask students to write down one key difference between local and global variables. Then, have them describe a scenario where using a global variable might be acceptable, and a scenario where it would be problematic.

Frequently Asked Questions

What is variable shadowing in Python?
Shadowing occurs when a local variable shares a name with a global one, hiding the global inside the function. The local takes precedence during execution there. Students avoid confusion by using distinct names or explicit parameters; prediction exercises reveal this behaviour clearly when outputs differ from expectations.
Why avoid overusing global variables?
Globals couple functions tightly, complicating debugging and testing in large programs. Changes ripple unpredictably. Encourage passing arguments for modularity; refactoring activities show cleaner code runs identically but scales better, aligning with professional Python practices.
How do you declare a global variable inside a function?
Use the 'global' keyword before assigning, like 'global x; x = 5'. Without it, Python treats the name as local. Whole-class live coding confirms this, as students see errors without 'global' and success with it, solidifying the rule.
How can active learning help students master variable scope?
Active approaches like pair predictions and debug relays provide instant interpreter feedback, contrasting expected vs actual outputs. Students hypothesise, test, and adjust, making scope rules observable. This beats passive reading, as collaborative fixes and live demos build debugging intuition vital for KS3 programming progression.