Play Home Contribute Github Join Us! Discourse Staff Members Github Contribution Guides Team

Reindeer Spotter

Hi folks,

I’ve passed this level, but I have a question about the statement “break”, I don’t quite understand why it’s placed there in my codes, of course I put it there by following the instructions, but can anybody help explain that? thanks

# This array contains each of the pen's positions.
penPositions = [ {'x':20,'y':24}, {'x':28,'y':24}, {'x':36,'y':24}, {'x':44,'y':24}, {'x':52,'y':24} ]

# This array is used to track which reindeer is in it.
penOccupants = [ 'empty', 'empty', 'empty', 'empty', 'empty' ]

# And this array contains our reindeer.
friends = hero.findFriends()

# Figure out which reindeer are already in their pens.
for deerIndex in range(len(friends)):
    reindeer = friends[deerIndex]

    # Check each pen if it matches a reindeer's pos.
    for penIndex in range(len(penPositions)):
        penPos = penPositions[penIndex]

        if penPos.x == reindeer.pos.x and penPos.y == reindeer.pos.y:
            # Put the id in penOccupants at penIndex.
            penOccupants[penIndex] =
            # break out of the inner loop here.

# Tell Merek what's in each pen.
for occIndex in range(len(penOccupants)):
    # Tell Merek the pen index and the occupant.
    # Say something like "Pen 3 is Dasher"
    hero.say("Pen " + occIndex + 'is ' + penOccupants[occIndex])

The most common use for break is when some external condition is triggered requiring a hasty exit from a loop. The break statement can be used in both while and for loops. The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.

1 Like

It’s a good practice to break out of a loop when the conditions being tested for have been met…after all, why continue running the code when you don’t need to?

1 Like

Thanks you all for the explanation:)

1 Like