How to create a trigger to detect that a variable has changed value within a loop?

Asked

Viewed 53 times

-1

would like to know how I can create a trigger to rotate a function only when a specific variable changes value within a loop, only without needing to define a variable outside that loop, for example:

a = 0
a_anterior = 0
for i in range(20):
    if i == 5 or i == 9:
        a += 1

    if a != a_anterior:
        print('a trocou de valor em i =', i)
        a_anterior = a

in this case I needed to define an auxiliary variable (a_previous), but the program I am doing requires that I do it several times, so I keep declaring too auxiliary variable, I would like to know how to do this process without having to declare anything, I thank you in advance.

  • In your case, you can already put the function inside the if, even because the variable a, only exchange value if the if is true, so you already have a trigger for a function.

  • But would it be possible to do without being inside the if? because in the real case the values would be updated by other different functions, there is no way I do it

  • Maybe a global helper variable will help you, every time some value changes this variable

1 answer

1

a = 0
a_anterior = 0
for i in range(20):
    if i == 5 or i == 9:
        a += 1

    if a != a_anterior:
        print('a trocou de valor em i =', i)
        a_anterior = a

'''by testing the code with more test cases it has worked well,.'''

  • yes, but my doubt is how to make a code that does this without having to declare the variable a_previous, if possible

  • create a list with the variable 'a' then use iteration to add the value of 'a' inside the iteration you have already created, then create another iteration to see if the previous value list[x] is different from list[x-1].

  • In that case, should I store all the valuables I’ve already owned on the list? because in the real example the "a" changes value hundreds of times, then it would be impossible to store all these values in a list

  • Yes, the idea was to store all the values of a in a list.

  • Would have some way to do it without storing any value?

  • If there is no knowledge.

  • I understand, thank you in every way friend

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.