Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
622 views
in Technique[技术] by (71.8m points)

python - Variable not changing after assigning another value to its dependent variable

Entering the following code into Python 3.5 shell gives me an answer I didn't expect, very basic I know but would somebody help me with an explanation please.

>>> x = 5
>>> y = 2
>>> a = x*y
>>> x,y,a
(5, 2, 10)

>>> x = 3
>>> x,y,a
(3, 2, 10)

These were all on separate lines each preceded by >>>

I expected 6, but the "new" x has not been used.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The 'a' variable will only be updated if you update it deliberately. In order to update 'a' after you have changed 'x', you will need to execute the line a = x*y again.

If you copy and paste your code into here http://www.pythontutor.com/visualize.html#mode=edit it will give you a good visualization of what is going on!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...