Variable as counter

my aim is simple. I want to make variable that retains its value and work as counter, say, from 1 to 500

I used the following function, but nothing happened, no error

def ch(self):
if self.ids.ch1.active:
counter = 1
counter = operator.add(counter,1)
print(counter)

Hi,

the way that you have your example set up it appears as if you want a function that keeps track of a variable every time that it is called (if I misunderstood this, please correct me and elaborate further).

You can do this by employing a function technique called closure functions. It works something like this:


def return_count(init):  

    counter = init      # initialize counter value

    def increment_counter():

        nonlocal counter
        counter += 1
        return counter

    return increment_counter

cnt_value = return_count(0)

# Every time that it is called, it increments the value by one
count_tracker = cnt_value()
count_tracker = cnt_value()
count_tracker = cnt_value()
count_tracker = cnt_value()

print(count_tracker)

cnt_value = return_count(0)  # Reset counter if needed

count_tracker = cnt_value()
count_tracker = cnt_value()

print(count_tracker)

As an fyi, when entering your code, please use the following format:

1 Like

why you repeated this four times

count_tracker = cnt_value()

count_tracker = cnt_value()

count_tracker = cnt_value()

count_tracker = cnt_value()

I need to increment the variable by one on button_press and use
that variable to navigate through database recordset

Hello,

note that it was just for demonstration purposes. You can do as you need in your code. In the following example (please make a note of that, just an example), I will show how you can keep track of the number of times two buttons have been pressed using this technique:

def return_count(init):  

    counter = init      # initialize counter value

    def increment_counter():

        nonlocal counter
        counter += 1
        return counter

    return increment_counter

cnt_value = return_count(0)

button_press_counter = 0  # Keep track of no. of times buttons
                          # were collectively pressed

def press_button1():

    global button_press_counter
    button_press_counter = cnt_value()

def press_button2():

    global button_press_counter
    button_press_counter = cnt_value()

press_button1()  # Press button 1
press_button2()  # Press button 2

print('\nTotal number of times buttons were pressed: ', button_press_counter)