MCS-201 · Unit 11

Functions and File Handling in Python

Section 2 of 8

Block 3 · Unit 11Functions and File Handling in Python8 min · Section 2 of 8

11.2Variable Scope: Local, Global and Nonlocal

Covers IGNOU MCS-201 §11.3

The scope of a variable is the part of the program in which its name can be used. Scope rules decide which variable a name refers to when the same name exists in several places.

Local and global variables

Local variableGlobal variable
CreatedBy assignment inside a function (parameters are local too)By assignment at the top level of a module
VisibleOnly inside that functionEverywhere in the module, including inside functions (for reading)
LifetimeCreated when the function is called, gone when it returnsAs long as the program (module) runs

The LEGB rule

When Python meets a name, it looks for it in four scopes, in this order:

LEGB name lookup
L  Local      names assigned in the current function
E  Enclosing  names in any outer function (for nested functions)
G  Global     names assigned at the top level of the module
B  Built-in   names Python provides: print, len, range, ...

The first match wins; if none matches, NameError is raised.

Changing an outer variable

The key rule: if a function assigns to a name anywhere in its body, that name is local to the whole function, unless it is declared otherwise.

  • Reading a global inside a function works.
  • Assigning to the same name inside the function creates a new local variable that hides the global.
  • Doing x = x + 2 inside a function, without a declaration, fails with UnboundLocalError, because x is local and is read before it has a value.
  • global x makes x refer to the module’s global variable (and can create it).
  • nonlocal x makes x refer to the variable of the nearest enclosing function.

Key takeaways

  • Scope = where a name can be used.
  • Lookup order: Local, Enclosing, Global, Built-in.
  • Assignment inside a function creates a local variable.
  • global and nonlocal let a function rebind outer variables.

Practice questions

Answer on paper first, then check. The explanation matters more than the letter you chose.

Question 1 · multiple choice

Where can a local variable be used?

Show answer

Answer: B. Only inside the function in which it is created

A local variable exists only while its function runs and is visible only inside it.

Question 2 · multiple choice

Which keyword lets a function rebind a module-level variable?

Show answer

Answer: C. global

global refers to the module scope; nonlocal refers to an enclosing function’s scope. static and extern are C keywords.

Question 3 · multiple choice

What does this program print?

Python · quiz_scope.py
n = 10

def f():
    n = 20
    return n

print(f(), n)
Show answer

Answer: C. 20 10

n = 20 creates a local n; the global n stays 10.

Question 4 · multiple choice

Which error does this function raise when called?

Python · quiz_unbound.py
total = 0

def add(v):
    total = total + v

add(5)
Show answer

Answer: D. UnboundLocalError

Because total is assigned in the function, it is local throughout the function, so reading it on the right side fails before it has a value.

Question 5 · multiple choice

In what order does Python search scopes for a name?

Show answer

Answer: A. Local, Enclosing, Global, Built-in

This is the LEGB rule; the innermost scope is searched first.

Question 6 · short answer

Write a function deposit(amount) that adds amount to a global variable balance, and explain why the declaration is needed.

Show worked answer

balance = 0, then def deposit(amount): global balance followed by balance += amount. Without global balance, the statement balance += amount assigns to balance, which makes it local to the function; it would then be read before having a value and raise UnboundLocalError. The declaration tells Python that balance means the module-level variable.

↑ ↓ move↵ openTab switch type