Dark theme

Finally, let's think about running away! At the moment, any fight is a fight to the death, but it would be nice if we could avoid a dangerous fight. There's actually a couple of ways of leaping out of a loop.

The keyword continue will leap you to the start of a loop from the middle of it, but break will leap you out of it altogether. Here's how we could use it...

def fight(monster_strength, monster_name):
    global player_strength
    count = 0
    while player_strength > 0 and monster_strength > 0:
        count = count + 1
        print("You FIGHT the", monster_name)
        print("SMASH!")
        time.sleep(500)
        print("BASH!")
        time.sleep(500)
        print("Oo!")
        time.sleep(500)
        random_number = random.randint(10)

        if player_strength > random_number:
            print("You won! Gain one strength!")
            player_strength = player_strength + 1
            monster_strength = monster_strength - 1
        else:
            print("You lost! Lose one strength!")
            player_strength = player_strength - 1
            monster_strength = monster_strength + 1
    if player_strength < 1:
        print("Oh no! You died!")
        sys.exit()
    else:
        answer = input("Do you want to run away? [Y][N]")
        if answer == "Y" or answer == "y":
            break
    return count

break will leap the code out of the while loop. The next line after this is return count.

[Home > Part 4 > Next]