'How do I check if a variable has gone up?
here is some code. I want to make an if statement but only when a variable has increased
while True:
a += 1
if a ????
print('a has changed')
Solution 1:[1]
Here is an option.
while True:
previous = a
# do stuff
a += 1
if a != previous:
print('a has changed')
Solution 2:[2]
Here is a way you can do this:
while True:
old_a = a #Create a variable for the old value of a
a += 1
if a > old_a: #Check the condition if value of a has increased.
print('a has changed')
Solution 3:[3]
A more clever way using the python Observer pattern.
class observe_value_change():
def __init__(self):
self._initial = 1
@property
def position(self):
return self._initial
@position.setter
def position(self, new_value):
self._initial = new_value
print("execute more code here!")
print(self._initial)
To test
p = observe_value_change()
print(p.position)
p.position = 4
Explanation: When the value of position changes, it will call the position setter method otherwise it will not be called. So, the if block can be written inside the position setter method.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Abhyuday Vaish |
| Solution 3 | Dharman |
