ProceduralOCR J277
DashboardCoursePracticeReviewProgressGlossary
Saved on this deviceContinue learning

Procedural · OCR J277 programming practice

Progress stays in this browser unless you export it.

Course/Procedures & functions/Local and global variables
J277 · 2.2.3

Unit 9 · Lesson 4

Local and global variables

Lesson progress0 / 7

Build the idea

Start with the concept and its key vocabulary.

Key idea

Distinguish local and global scope and modify a global variable using the correct syntax.

Variables created inside a sub-program are local: they can be used only within that sub-program and are removed when it finishes. Parameters are local too. A global variable is declared in the main program. ERL marks it with global; Python uses global inside a function when that function changes the global value. Prefer parameters and returned values because widespread global state is harder to debug.

Scope

The part of a program in which a variable can be accessed.

Local variable

A variable created inside a sub-program and accessible only there.

Global variable

A variable declared outside sub-programs and accessible throughout the program.

Lifetime

The time for which a variable exists in memory.

Keep these in mind

  • Local variables cannot be accessed outside the sub-program that created them.
  • Parameters are local variables.
  • ERL declares a global with global name = value.
  • Python needs global name inside a function before assigning to that global.
  • Local data and parameters reduce naming conflicts and hidden changes.

Learning objective

Distinguish local and global scope and modify a global variable using the correct syntax.

Exam tip

When explaining scope, say where the variable is declared, where it can be accessed and when it is removed from memory.

Common mistake

A local calculation cannot be printed later by name from the main program. Return it and store the result instead.

PreviousNext