LearnFrenzy
Sign in Take a free test

Functions · Predict the Output · Question 8

nonlocal in a nested function Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

What is the output of the following Python program?

main.py
def outer():
    n = 0
    def inner():
        nonlocal n
        n += 1
        return n
    inner()
    inner()
    return inner()

print(outer(), outer())
  • A 3 6
  • B 3 3 Correct
  • C 1 1
  • D 2 2
Correct Answer: Option B

Each call of outer creates a fresh n starting at 0; inner runs three times and returns 3.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links