Skip to main content
 首页 » 编程设计

python之在 while 循环中访问变量

2025年05月04日8linjiqin

我在使用循环计算粒子之间的距离时卡住了。到目前为止,我有下面的代码。除了最后输入的点之外,我似乎无法访问任何点。最后的打印只是打印最后一个。

除了最后一个输入的点之外,有什么方法可以访问输入的点的位置吗?

#user location 
xu = int(input('X coordinate of user: ')) 
yu = int(input('Y coordinate of user: ')) 
zu = int(input('Z coordinate of user: ')) 
#number of particles 
count = int(input()) 
icount = 0 
while icount < count: 
    x=  int(input('particle x coordinate: ')) 
    y = int(input('particle y coordinate: ')) 
    z = int(input('particle z coordinate: ')) 
    q = int(input('particle charge: ')) 
    icount += 1 
print( x, y, z)         

请您参考如下方法:

实际上,它只会打印最后一点。

您正在遍历整个集合,一旦完成迭代,x、y、z 中存储的唯一值是那些包含在你最后一个元素中的东西。

这是为什么?

因为,每次存储新值时,都会覆盖旧值。

如果您在循环中包含您的 print 调用,您将显示所有值:

while icount < count: 
    x = int(input('particle x coordinate: ')) 
    y = int(input('particle y coordinate: ')) 
    z = int(input('particle z coordinate: ')) 
    q = int(input('particle charge: ')) 
    icount += 1 
    print( x, y, z)