如果变量的值包含递增的数字,为什么变量的值不改变?

时间:2019-08-20 16:42:35

标签: python

我有一个应该显示两个数字之和的变量。当我尝试增加一个数字时,总和保持不变,但是数字已经增加了。

Size1 :20 
Frequency1: 60 
Size2 :30
Frequency2:70 
Size3 :40
Frequency3:80
 Size4 :
Frequency4: 
Size5 :
Frequency5:

我希望结果是这样的:

x = 1

test = 0 + x

while x <= 5:
    print('the result is',test)
    x+=1

但我却得到:

the result is 1
the result is 2
the result is 3
the result is 4
the result is 5

谢谢!

4 个答案:

答案 0 :(得分:2)

为表达式分配变量只会复制表达式的值,并不会使变量始终重新评估该表达式。

如果您想要重新计算,请使用一个函数。

x = 1
test = lambda: 0 + x

while x <= 5:
    print('The result is', test())
    x += 1

或者您可以将分配放在循环中:

x = 1

while x <= 5:
    test = 0 + x
    print('The result is', test)
    x += 1

答案 1 :(得分:0)

您期望test每次更改x都会发生变化,但这不是变量的工作方式。为变量分配值后,该值将不会更改(数组等可变对象除外,但这不是我们要在此处处理的内容)。您应该打印test而不是x,或者也重新分配test变量。

您的代码应为:

x = 1

test = 0 + x

while x <= 5:
    print('the result is', x) # modified line
    x+=1

答案 2 :(得分:0)

你很困惑2件事。

test = 0 + x行不是等式。这与数学不同,y = mx + ny为每个x获取多个值。

这是作业。这意味着test的值是{{1}的0+x的值是0+1,所以在程序分配1的值并计算右边之后您将获得x的作业,仅此而已。

这是编程的工作方式。祝你好运!

答案 3 :(得分:0)

原因是各行的位置,order of executiontest = 0 + x运行并且test存储该值并成为int值。在while循环中仅显示值,x对此值无效。

解决此问题的一种方法是使测试成为函数。

def test(value): 
    new_value = 0 + value
    return new_value

x = 1
while x <= 5:
    print('the result is', test(x))
    x += 1

或者使循环在每次执行时都执行。

x = 1

while x <= 5:
    test = 0 + x
    print('the result is', test)
    x += 1