-2

可能的重复:
Python 提前离开循环

所以,我在 python 中有一个循环,我需要它从另一个数字中获取一个数字,直到它为负数,并且每次减去时都有一条消息。问题是,如果变量符合第一个条件,它将通过整个循环来拟合条件并每次打印消息。

sb = bosshp12 - final
if sb <= 0:
    print( 'You need to do 1 second of damage to get a 4% Soulbound. ' )
sb - final
if sb <= 0:
    print( 'You need to do 2 seconds of damage to get a 4% Soulbound. ' )

因此,如果数字已经< 0在第一个 if 语句中,它仍然会通过。我希望循环在之后中断sb <= 0

4

1 回答 1

0

如果我做对了,所有代码都在一个while循环下,你可以使用break语句

sb = bosshp12 - final
    if sb <= 0:
            print( 'You need to do 1 second of damage to get a 4% Soulbound. ' )
            break
    sb - final
    if sb <= 0:
            print( 'You need to do 2 seconds of damage to get a 4% Soulbound. ' )

哦,elif 语句似乎也可以满足您的需要?

sb = bosshp12 - final
        if sb <= 0:
                print( 'You need to do 1 second of damage to get a 4% Soulbound. ' )
        sb - final
        elif sb <= 0:
                print( 'You need to do 2 seconds of damage to get a 4% Soulbound. ' )

这样,如果 sb <=0 在第一次检查时为 True,则不会检查第二次。

于 2012-04-22T13:50:11.110 回答