Suppose I have the code:
a = 2
b = a + 2
a = 3
The question is: how to keep b
updated on each change in a
? E.g., after the above code I would like to get: print(b)
to be 5
, not 4
.
Of course, b
can be a function of a
via def
, but, say, in IPython it's more comfortable to have simple variables. Are there way to do so? Maybe via SymPy
or other libraries?
Reassigning variablesValues can be reassigned to variables in Python. When variables are reassigned, their value changes to that of the newer value specified, and the previous value is lost. Let's look at an example. We can reassign variable values in Python as follows.
You can do a lambda, which is basically a function... The only malus is that you have to do b()
to get the value instead of just b
>>> a = 2
>>> b = lambda: a + 2
>>> b()
4
>>> a = 3
>>> b()
5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With