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

Python 如果一个变量包含一个递增的数字,为什么它的值不改变?,python,Python,我有一个变量,用来表示两个数的和。当我尝试增加其中一个数时,和保持不变,但是这个数已经增加了 x = 1 test = 0 + x while x <= 5: print('the result is',test) x+=1 但我得到的却是: the result is 1 the result is 1 the result is 1 the result is 1 the result is 1 提前谢谢 您希望每次更改x时测试都会更改,但变量不是这样工作的。一

我有一个变量,用来表示两个数的和。当我尝试增加其中一个数时,和保持不变,但是这个数已经增加了

x = 1

test = 0 + x

while x <= 5:
    print('the result is',test)
    x+=1
但我得到的却是:

the result is 1
the result is 1
the result is 1
the result is 1
the result is 1
提前谢谢

您希望每次更改x时测试都会更改,但变量不是这样工作的。一旦你给一个变量赋值,除了数组这样的可变对象之外,它不会改变,但这不是我们这里要讨论的。您应该打印test而不是x,或者重新分配test变量

您的代码应该是:

x=1 测试=0+x
当x为变量赋值时,表达式只会复制表达式的值,而不会使变量始终重新计算该表达式的值

如果您想要重新计算的东西,请使用函数

x = 1
test = lambda: 0 + x

while x <= 5:
    print('The result is', test())
    x += 1
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

你有两件事

测线=0+x不是一个方程式。这不像数学中y=mx+n,y为每个x得到多个值

这行是作业。这意味着test得到的值是0+x,也就是0+1,也就是1,所以在程序分配了x的值并计算了赋值的右边之后,你得到test=1,就是这样


这就是编程的工作原理。祝你好运

原因是行的位置,test=0+x运行,test存储该值并成为int值。在while循环中,只打印值,x对其没有影响

解决此问题的一种方法是将测试设置为函数

x = 1
test = lambda: 0 + x

while x <= 5:
    print('The result is', test())
    x += 1
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

执行test=0+x后,变量test将获得一个值。它不知道,如果你改变x,它也应该改变。。。为什么你们甚至需要测试?把测试放在你们的循环中,它应该会起作用。为什么这个问题会被否决?它显示了大量的代码、MCVE和接收/预期输出,并清楚地说明了问题。这不是OP所要求的。他们想要一种方法,让一个变量引用另一个变量,当引用一个变量时,两个变量都会发生变化。考虑一种C++语言,在这里你可以使用指针来完成任务。编辑:您的编辑解决了OP的实际问题。这不是很清楚。最接近于指定指针的是test=x,而不是test=0+x。但是,在OP编辑其帖子之前,我不确定OP想要做什么。