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