将另一个值分配给其因变量后变量不会改变 [英] Variable not changing after assigning another value to its dependent variable

查看:33
本文介绍了将另一个值分配给其因变量后变量不会改变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 3.5 shell 中输入以下代码给了我一个我没想到的答案,我知道非常基本但有人能帮我解释一下吗.

<预><代码>>>>x = 5>>>y = 2>>>a = x*y>>>x,y,a(5, 2, 10)>>>x = 3>>>x,y,a(3, 2, 10)

这些都在单独的行上,每行都以 >>>

开头

我期望是 6,但尚未使用新"x.

解决方案

a = x*y 不是一个在您更改 时自动更新 a 的方程式>xy.当语句运行时,它将 a 设置为 x*y 一次.之后对 xy 的任何更改都不会影响 a.

当您更改xy 时,您需要手动更新a,或者,如果情况允许,请使用本地函数做@Silvio 的回答所显示的事情.创建本地快捷方式来帮助清理代码很方便.

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.

解决方案

a = x*y isn't an equation that automatically updates a whenever you change x or y. It sets a to x*y once when the statement is run. Any changes to x or y afterward have no effect on a.

You'll need to manually update a when you change x or y, or, if the situation allows it, use local functions to do what @Silvio's answer shows. It's handy to create local shortcuts to help clean up code.

这篇关于将另一个值分配给其因变量后变量不会改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆