Courseiva

PCEP Computer Programming and Python Fundamentals Practice Question

Consider code:

def outer():

x = 1

def inner():

nonlocal x x = 2 inner()

print(x)

outer() What is printed?

⚠ Common exam trap

The PCEP exam often tests the distinction between `nonlocal` and `global`, and the trap here is that candidates mistakenly think `nonlocal` is unnecessary or causes an error, or they assume the inner assignment creates a separate local variable that does not affect the outer scope.

Answer choices

Why each option matters

Answer the question above first, then reveal the full breakdown to understand why each option is right or wrong.

Correct answer & explanation

✓

2

The `nonlocal` declaration inside `inner()` binds the variable `x` to the `x` defined in the enclosing `outer()` function. When `inner()` assigns `x = 2`, it modifies that outer `x`, so after `inner()` returns, `print(x)` in `outer()` outputs 2.

Answer analysis

Option-by-option breakdown

For each option: why learners choose it and why it is or isn't the right answer here.

  • ✓

    2

    Why this is correct

    The `nonlocal x` declaration binds `inner`'s assignment to the enclosing `outer` function's variable, not a new local one. So `x = 2` mutates the same cell that `print(x)` reads after `inner()` returns, satisfying the stem's requirement that the enclosing scope's value be updated. Output is 2.

  • ✗

    1

    Why it's wrong here

    nonlocal x makes inner's assignment mutate outer's variable, so 2 is printed, not 1. Printing 1 would require inner to omit nonlocal and create its own local x, leaving outer's x untouched at its initial value.

  • ✗

    Error

    Why it's wrong here

    The nonlocal declaration rebinds outer's x to 2, so no error occurs; the call prints 2. Error would arise only from referencing an unbound name, such as declaring global x without an existing module-level binding, or assigning before nonlocal.

  • ✗

    None

    Why it's wrong here

    The function prints 2: nonlocal rebinds the enclosing x, and outer() returns None only as its own value, which is never printed. None would appear solely if the code printed the call's result, as in print(outer()).

About these practice questions

One of 482 original PCEP practice questions on Courseiva, each with a full explanation and wrong-answer analysis — not exam dumps or protected exam content. Learn why practice questions differ from exam dumps →

How Courseiva writes practice questions · Editorial policy

JA

Written by Johnson Ajibi, MSc IT Security

Senior Network & Security Engineer · founder of Courseiva

This PCEP practice question is part of Courseiva's free Python Institute certification practice question bank. Courseiva provides original exam-style practice questions with explanations, topic-based practice, mock exams, readiness tracking, and study analytics to help learners prepare for the PCEP exam.