Local and Global

Scope is the region of a program where a name can be seen. A variable created inside a function is local to it. It is born when the function is called and it dies when the function returns. Code outside the function cannot see it at all.

A variable created at the top level of a file is global. Every function in that file can read it.

Local scope

PYTHON

def greet():
    message = "Akwaaba"
    print(message)

greet()
print(message)  # NameError

JAVASCRIPT

function greet() {
  let message = "Akwaaba";
  console.log(message);
}

greet();
console.log(message); // ReferenceError
Compare → Both languages agree completely here. `message` exists only inside `greet`. Asking for it outside is an error in Python and in JavaScript. The wording of the error differs, the rule does not.
EXAMPLE
loading editor…
YOUR TURN
Your turn → Now add print(message) as the last line and run it again. Read the error carefully, it is telling you exactly what scope means.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

✦ Why this is a feature, not an obstacle

Local scope means you can name a variable `total` inside twenty different functions and none of them collide. Without it, every name in a large program would have to be unique. Scope is what makes code composable.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Shadowing and Parameters →
← Back