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

How do I change a variable inside a function ever iteration of a loop?

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

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

while True:
    click()
    print(alternate) #constantly prints False

while what I wanted was to print True, False, True, etc.

>Solution :

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