在嵌套循环中只打印一次

2024-05-13 17:59:34 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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!'

我不想重复的部分是最后三个print语句,我尝试过break语句,但这段代码是一个嵌套循环,当它被重新循环时,它会在break之前重新开始。在


Tags: ofinposlayerstep粒子randommath
2条回答

试试这个。你的代码应该是while循环的一部分。如果不是,请将out_of_layer移到下一个外循环之前。在

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

对于pho是什么类,创建一个名为printed的属性,并将其初始化为False。然后,在第一次打印时将其设置为True,然后说

if d > 10 and not pho.printed

而不是仅仅if d > 10。在

相关问题 更多 >