How to change variable in function scope from inner function

Question:

Same code will work in JS, but in python it will not change variable, how do you change variables in nested functions? Thanks in advance and sorry for noob question

   def sample():
       a = False
       def sample2():
           a = True
       sample2()
       return a

Answers:

Use nonlocal to modify variables outside the scope of the function.

   def sample():
       a = False
       def sample2():
           nonlocal a
           a = True
       sample2()
       return a
Answered By: paltaa

use nonlocal

def sample():
    a = False
    def sample2():
        nonlocal a
        a = True
    sample2()
    return a

Python 3 docs

The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals.

Answered By: imbr
 def sample():
       a = False
       def sample2():
           nonlocal a
           a = True
       sample2()
       return a

This should work.

Answered By: Hasibul Islam Polok
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.