0

I have this project, in which I have a single counter, which counts throughout the whole program. I have several functions, in which this counter appears. The problem is, how do I get the counter value from another function?

The situation is pretty much like this. The counter already has a previous value:

def function1(counter):
    if logic:
        function2(counter)
    print("...", counter, "...")
    # following code
    # function1 should continue with the updated counter value

def function2(counter):
    while logic1
        if logic2
             counter += 1

Et cetera. I hope you understood.

  • possible duplicate of [Python: How do I pass a variable by reference?](http://stackoverflow.com/questions/986006/python-how-do-i-pass-a-variable-by-reference) – Ashwini Chaudhary Feb 10 '14 at 12:55
  • Perhaps return the counter from `function2`: `counter = function2(counter)` ? –  Feb 10 '14 at 12:57
  • 1
    eh, what's the problem with `new_counter = function2(counter)`? – laike9m Feb 10 '14 at 12:58
  • What does the counter actually accomplish? – John Zwinck Feb 10 '14 at 13:01
  • @Evert: thanks, that seemed to solve the problem! I thought I had already tried your solution, but I guess I screwed up. – user3292808 Feb 10 '14 at 13:09
  • @John Zwinck: When the counter reaches a certain value, the program eventually quits – user3292808 Feb 10 '14 at 13:10
  • @laike9m: The counter value is used by several functions at different points so I wouldn't like to change the variable's name - it would end up in a gazillion different variable names for the same counter – user3292808 Feb 10 '14 at 13:11

1 Answers1

0

well, first of all

while logic
        if logic
             counter += 1

does not make a lot of sense.. the while already tests for the logic, no?

to answer your question, the most obvious way would be for function2 to return the counter, but you could consider using classes and putting the counter as a member value for a more OOP approach.

WeaselFox
  • 7,220
  • 8
  • 44
  • 75