打破Python循环,不间断

时间:2015-08-19 23:23:02

标签: python loops while-loop break

在下面的代码中,为什么当战斗设置为False时它不会停止循环?

我知道它不会停止循环,因为当战斗设置为False时它不会进入战利品部分。这是整个循环:

while fighting:
    cls()
    print("The enemy has", opponent.HP, "HP!")
    input()
    if int(opponent.HP) <= 0:
        print("Yep yep")
        winner = True
        fighting = False
    elif int(ownedCreatures[activeCreature].HP) <= 0:
        winner = False
        fighting = False
    showFight(opponent, activeCreature)
    allowed = ["a", "i", "r"]
    choice = input(">>")

    while not choice in allowed:
        choice = input("Try again please >>")

    if choice.lower() == "a":
        if previousTurn == "Not defined":
            num = random.randint(1, ownedCreatures[activeCreature].support + opponent.support)
            if num <= ownedCreatures[activeCreature].support:
                attacker = "player"
                previousTurn = "player"
            else:
                attacker = "opponent"
                previousTurn = "opponent"
        else:
            if previousTurn == "player":
                attacker = "opponent"
                previousTurn = "opponent"
            else:
                attacker = "player"
                previousTurn = "player"

        attack(attacker, activeCreature, opponent)

    #if choice.lower() == "i":

    if choice.lower() == "r":
        num = random.randint(1, ownedCreatures[activeCreature].support + opponent.support)
        if num <= ownedCreatures[activeCreature].support:
            cls()
            print("-------------------------------------------")
            print("You succesfully escaped this horrible fight!")
            print("-------------------------------------------\n")
            input("Press Enter to continue... >> ")
            winner = "Not defined"
            fighting = False
        else:
            cls()
            print("-------------------------------------------")
            print("Think you can run that easily?")
            print("-------------------------------------------\n")
            input("Press Enter to continue... >> ")

#After the fight
if winner == True:
    cls()
    loot()
elif winner == False:
    cls()
    print("-------------------------------------------")
    print("You have lost the fight!")
    print("You lost 50 Serra!")
    serra = serra - 50
    if serra < 0:
        serra = 0
    print("-------------------------------------------\n")
    input("Press Enter to continue... >> ")

1 个答案:

答案 0 :(得分:1)

循环中有三个位置,您将fighting设置为False,所有这些位置都带有if条件:

  1. int(opponent.HP) <= 0
  2. int(ownedCreatures[activeCreature].HP) <= 0
  3. num <= ownedCreatures[activeCreature].support
  4. 第一个和第二个条件在循环内是恒定的,因此如果它们开始False,则永远无法访问fighting的更改。

    第三个:num是一个大于1的随机数,因此如果ownedCreatures[activeCreature].support0,则无法访问该条件。

    打印条件值以检查它们是否已满足。