Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Revalue local variable in python function

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading