Luke Armstrong
Luke Armstrong

Reputation: 13

Python Variables and Equations

So I'm pretty new to Python and coding in general, however I was messign around with some bisection stuff and I came across a problem. I have this code:

a = 1
b = 2
c = 0

fa = a**3-a-2
fb = b**3-b-2
fc = c**3-c-2

c += 2
print(fc)

The problem is that when I run it, the 'c' variable changes but 'fc' stays the same and outputs -2, when it should output 4 instead. No matter what I've tried, fc alwas stays the same and updating c does nothing to change fc, even though I believe it should?

Upvotes: 1

Views: 112

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121834

Python stores the outcome of the expressions in fa, fb and fc, not the expressions themselves:

>>> a = 1
>>> b = 2
>>> c = 0
>>> fa = a**3-a-2
>>> fb = b**3-b-2
>>> fc = c**3-c-2
>>> fa
-2
>>> fb
4
>>> fc
-2
>>> type(fc)
<class 'int'>

If you wanted to re-run an expression for changing variables, create functions. For a single expression, you can create a function object by using a lambda expression:

fa = lambda: a**3-a-2
fb = lambda: b**3-b-2
fc = lambda: c**3-c-2

These 3 functions expect a, b and c to exist in their parent scope. Now changing c and then calling the function will re-run the expression:

c += 2
print(fc())  # note the (), calling the function

Demo:

>>> fa = lambda: a**3-a-2
>>> fb = lambda: b**3-b-2
>>> fc = lambda: c**3-c-2
>>> fa
<function <lambda> at 0x10979dd90>
>>> fb
<function <lambda> at 0x1097b1e18>
>>> fc
<function <lambda> at 0x1097b1ea0>
>>> fc()  # calling a function executes the expression, each time
-2
>>> c += 2
>>> fc()
4

Upvotes: 1

Related Questions