0

I write this code:

a=5
b=4
s=a*b
print(s)
20

then I changed variable "a" to 6:

a=6
print(s)
20

I changed variable "a" and when i say print(a) it shows new variable(6) but when I say print(s) it shows the same number(20) I wonder why this happens. I expected it shows me s=24 but why it shows 20 again?

Georgy
  • 12,464
  • 7
  • 65
  • 73
hgs
  • 141
  • 7
  • 2
    Because `s` is `20`. It doesn't _magically_ change. – tkausl May 18 '20 at 07:27
  • 1
    why should it show something different? If you change your address, do all your bills magically appear at your new address? – Sayse May 18 '20 at 07:30
  • because we changed "a" and "s" value is depend on the value of "a" – hgs May 18 '20 at 07:31
  • 1
    It is not at all "dependent" on the value of `a`. Its value is calculated by it, **once**, and that's it. The first line of `s` is equivalent to `s = 5 * 4`. It is not aware that this value came from `a` and doesn't care if it changes – Tomerikoo May 18 '20 at 07:40
  • Does this answer your question? [Variable not changing (Python 3.5)](https://stackoverflow.com/questions/46374966/variable-not-changing-python-3-5). Also related: https://stackoverflow.com/questions/13530998/are-python-variables-pointers-or-else-what-are-they – Tomerikoo May 18 '20 at 07:42
  • thank you guys I understand – hgs May 18 '20 at 07:44

3 Answers3

3

This is a very reasonable question to ask. The reason it does not change is that s gets the result of the calculation a*b, and does not represent the actual function a*b. This is just how python works and can be different from other languages.

You can achieve something similar to what you want by using a lambda:

a=5
b=4
s=lambda: a*b
print(s()) # prints 20
a=6
print(s()) # prints 24

note that you will have to call the lamdba using s().

John Sloper
  • 1,813
  • 12
  • 14
0

You have to calculate s again to change s.

a=6
s=a*b
print(s)
Sahit
  • 53
  • 1
  • 4
0

After you changed a=6 you have to compute s=a*b again to take in account the new value of a.

Ale
  • 917
  • 9
  • 28