I'm trying to have a boolean variable flip (True becomes False, False becomes True), and this variable is inside of a function. However, I have an issue where I either have to assign the variable inside the function (thus having the variable reset to what I assigned it to inside the function), or don't do that, which causes an UnboundLocalError. Any help on this would be great.
I was creating a function, click(), which flips a boolean every iteration of a loop
def click():
alternate = True #not doing this will cause an error
alternate = not alternate #flipping the variable
and then having a loop run using the function
while True:
click()
print(alternate) #constantly prints False
while what I wanted was to print True, False, True, etc.
CodePudding user response:
python does not have pass by reference. it has mutable and immutable variables. so if your variable is mutable you need to return the value each time and reset it like this:
def click(alternate):
alternate = not alternate #flipping the variable
return alternate
and:
alternate = True
while True:
alternate=click(alternate )
print(alternate) #constantly prints False
CodePudding user response:
You can use a global variable alternate
ex -
alternate = True #global varaible
def click():
alternate = not alternate #flipping the variable
while True:
click()
print(alternate) #prints False, True, False, True
or maybe pass the value of alternate
as an argument (if you have a restriction where click()
cannot access the variable).