Skip to content Skip to sidebar Skip to footer

Assigning Value To `x` Doesn't Calculate Sum

I have the following problem: x=Symbol('x') book={1:2*x,2:3*x} x=2 print(book) >>> {1:2*x,2:3*x} I had hoped it would print {1:4,2:6} But if I set book={1:2*x,2:3*x} jus

Solution 1:

You're dealing with two different values of x because you're talking about setting x to something other than Symbol('x') in one case but not the other. In one case:

x=Symbol('x') 
book={1:2*x,2:3*x}
x=2
print(book)

Result:

{1:2*x, 2:3*x}

x was Symbol('x') when you created book. It doesn't matter that you later set x to 2.

In your other case, if I understand you right:

x=Symbol('x')
x=2
book={1:2*x,2:3*x}
print(book) >>> {1:2*x,2:3*x}

Result:

{1:4, 2:6}

x is now 2 when you build book, so your result now has nothing to do with sympy. It's just regular Python arithmetic, and so you get computed values in your dict.

If what you want is {1: 4, 2: 6}, why are you using sympy at all?

To answer your final question, you're asking why adding the line book = book doesn't change the result. Why would it? That line doesn't do anything. book is the same value after that line is run that it was before.

Post a Comment for "Assigning Value To `x` Doesn't Calculate Sum"