I have this simple code, I want value of 'a' to be 4 at the end. 'global a' can solve it, but is there any other way? Since it's everywhere that overuse of globals is a symptom of poor design.
a=3
def function():
a = 4
function()
print(a)
I have this simple code, I want value of 'a' to be 4 at the end. 'global a' can solve it, but is there any other way? Since it's everywhere that overuse of globals is a symptom of poor design.
a=3
def function():
a = 4
function()
print(a)
If you want a to be 4 you have to return it from the function then reassign it to a.
a=3
def function(b):
b = 4
return b
a = function(a)
print(a)
Any names inside of a function are local to that function and as such you can perform a calculation inside the function independent of the rest of the code.
Once this is complete you can reassign back to the variable for further processing.
So maybe not just turn it to 4, you could do something like:
a=3
def function(b):
b = b ** 4 // 5
return b
a = function(a)
print(a)
Figured out a solution, that stores the variable in a class:
class aa:
def __init__(self):
self.a=3
variables = aa()
print(variables .a) # Prints '3'
def function():
z.a = 4
function()
print(variables .a) # Prints '4'