Python 在嵌套循环中仅打印一次

Python 在嵌套循环中仅打印一次,python,loops,break,vpython,Python,Loops,Break,Vpython,我正在模拟一个粒子在不同层中移动,一旦它在层中移动,我希望它打印一些东西。我的问题是粒子可以移回前一层并再次出来,这会触发它再次打印,我不想这样 while math.sqrt((pho.pos.x)*(pho.pos.x)+(pho.pos.y)*(pho.pos.y)+(pho.pos.z)*(pho.pos.z))<10: x=random.uniform(-j,j) y=random.uniform(-j,j) z=random.uniform(-j,j)

我正在模拟一个粒子在不同层中移动,一旦它在层中移动,我希望它打印一些东西。我的问题是粒子可以移回前一层并再次出来,这会触发它再次打印,我不想这样

while math.sqrt((pho.pos.x)*(pho.pos.x)+(pho.pos.y)*(pho.pos.y)+(pho.pos.z)*(pho.pos.z))<10:
    x=random.uniform(-j,j)
    y=random.uniform(-j,j)
    z=random.uniform(-j,j)
    step=(x,y,z)
    t=t+dt
    pho.pos=pho.pos+step
    print 'Step Number', t
    rate(speed)
    d=math.sqrt((pho.pos.x)*(pho.pos.x)+(pho.pos.y)*(pho.pos.y)+(pho.pos.z)*(pho.pos.z))
    '''if d>10:
        print pho.pos 
        print d 
        print 'Out of Layer 1 in',t,'steps!'
        break
    else:
        pass'''
d=math.sqrt((pho.pos.x)*(pho.pos.x)+(pho.pos.y)*(pho.pos.y)+(pho.pos.z)*(pho.pos.z))
print pho.pos
print d
print 'Out of Layer 1 in',t,'steps!'

当math.sqrt((pho.pos.x)*(pho.pos.x)+(pho.pos.y)*(pho.pos.y)+(pho.pos.z)*(pho.pos.z))在任何类
pho
上时,创建一个名为
printed
的属性,并将其初始化为
False
。然后,在第一次打印时将其设置为True,并说

if d > 10 and not pho.printed

如果d>10
,尝试这样的方法,而不是仅仅
。我认为你的代码应该是while循环的一部分。如果没有,将
移出\u层
到下一个外循环之前

out_of_layer = False  

while math.sqrt((pho.pos.x)*(pho.pos.x)+(pho.pos.y)*(pho.pos.y)+(pho.pos.z)*(pho.pos.z))<10:
    x=random.uniform(-j,j)

    ... blah blah stuff you already know about ...

    d=math.sqrt((pho.pos.x)*(pho.pos.x)+(pho.pos.y)*(pho.pos.y)+(pho.pos.z)*(pho.pos.z))
    if not out_of_layer:
        print pho.pos
        print d
        print 'Out of Layer 1 in',t,'steps!'
        out_of_layer = True
out\u of_layer=False
而数学sqrt((pho.pos.x)*(pho.pos.x)+(pho.pos.y)*(pho.pos.y)+(pho.pos.z)*(pho.pos.z))