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

Why does this simple python function only work once

I want to create a simple counter so i created this function:

count = 0

def add(count):
    count += 1
    print(count)

and if re-called the count goes up to 1 but if I recall it again it stays at 1.
I also tried to output the count variable outside of the function after recalling it but that led to a constant output of 0

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 :

The count variable in your function has a different scope to the count variable in the rest of your script. Modifying the former does not affect the latter.

You would need to do something like:

def add(count):
    count += 1
    print(count)
    return count

count = 0
count = add(count)
count = add(count)
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