-1

I was trying out a few things with scopes in python and came into a little problem. I have this code here. I want to change the variable var from within a nested function.

def func_1():
    var = 1
    
    def func_2():
        var = 2
        
    func_2()
    print(var)

func_1()

When func_1() is run, var is still 1. Is it possible to edit var under func_2?

Asocia
  • 5,935
  • 2
  • 21
  • 46
Paul
  • 107
  • 4
  • I'm downvoting because it took less than a minute of research to find an exact duplicate. Please research before posting. – Mad Physicist Dec 22 '20 at 16:36

1 Answers1

2

You can use nonlocal keyword:

def func_1():
    var = 1
    def func_2():
        nonlocal var
        var = 2
    func_2()
    print(var)

func_1() # prints 2
Asocia
  • 5,935
  • 2
  • 21
  • 46