Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Scope defines where variables can be accessed. What variables are within the scope of the inner2 function?

+6 votes
asked Feb 4, 2025 by Osman Tellez (180 points)

 
 def outer1(i):
  j = i + 1
  def outer2():
    k = j + 1
    def inner1():
      m = k + 1
      def inner2():
        n = m + 1
        return n
      m = inner2()
      return m
    k = inner1()
    return k
  j = outer2()
  return j
  
print ("outer1(1) = ", outer1(1))

1 Answer

0 votes
answered Feb 5, 2025 by Peter Minarik (101,420 points)

A pretty useful reading material on scopes in Python: https://www.w3schools.com/python/python_scope.asp

Not counting global and nonlocal variables (you do not have any of these by the way), in inner2 the following variables are visible:

def outer1(i):
  j = i + 1
  def outer2():
    k = j + 1
    def inner1():
      m = k + 1
      def inner2():
        n = m + 1
        return n
      m = inner2()
      return m
    k = inner1()
    return k
  j = outer2()
  return j
  
print ("outer1(1) = ", outer1(1))

That is, all the variables (i, j, k, m, n) is visible in inner2. See the "Function Inside Function" section in the above link.

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and receive answers from other members of the community.
...