-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?

1
  • I'm downvoting because it took less than a minute of research to find an exact duplicate. Please research before posting. Commented Dec 22, 2020 at 16:36

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

It works, thanks! :D

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.