0

I'm java script programmer and start to learn python. I try to revalue local variable in python function. My code :

def first_function():
    var1 = 5
    def second_function():
        var1 = 10
    second_function()
    print(var1)

first_function()

result this code is

5

but when second_function executed, var1 revalued with '10'. I search in google and find 'global' solution. How can I solve this issue without define global variable. Thanks.

1 Answer 1

2

Use nonlocal to have an inner function's name refer to a name in an outer function.

def first_function():
    var1 = 5
    def second_function():
        nonlocal var1
        var1 = 10
    second_function()
    print(var1)

first_function()

This is the inner function equivalent to the global keyword.

As with global, you only need nonlocal if you want to assign to the name. You can access the name just fine without nonlocal (just like you can access global names, such as print, without global).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.