Pythonic python -- looping over lists


#1

In levels like “Shine Getter” you are teaching players to write bad code. The template says:

coinIndex = 0
# Wrap this into a loop that iterates over all coins.
coin = coins[coinIndex]
# Gold coins are worth 3.
if coin.value == 3:
    # Only pick up gold coins.
    pass

This leads to

coinIndex = 0
while coinIndex < len(coins):
    coin = coins[coinIndex]
    # Gold coins are worth 3.
    if coin.value == 3:
        # Only pick up gold coins.
        pass
    coinIndex += 1

which is ugly, unidomatic python code. Instead one should end up with

for coin in coins:
    # Gold coins are worth 3.
    if coin.value == 3:
        # Only pick up gold coins.
        pass

#2

i think these for loops are never explained, or ive forgotten that. they were just used i think in the first or secon level woth Boss star 1. a beginner level would be great i think. can sb work on this?


#3

For loops were just introduced in the Mountain level Timber Guard. The Desert campaign focuses on while loops. :).


#4

can someone help on this its saying X underneath hero but not showing anything wrong in the text (if this is in the wrong place please tell me (new to this)):stuck_out_tongue:

loop:
    # Collect gold.
    coin = self.findItems()
    gold = self.findNearest( golds )
    self.moveXY( gold.pos.x , gold.pos.y)
    # If you have enough gold, summon a soldier.
    if self.gold > self.costOf("soldier"):
        self.summon("soldier")
    # Use a for-loop to command each soldier.
    # For loops have two parts: "for X in Y"
    # Y is the array to loop over.
    # The loop will run once for each item in Y, with X set to the current item.
    for friend in self.findFriends():
        if friend.type == "soldier":
            enemy = friend.findNearestEnemy()
            # If there's an enemy, command her to attack.
            if enemy:
                self.command( friend, "attack", enemy )
            # Otherwise, move her to the right side of the map.
            else:
                pos = {'x':82, 'y':33}
                self.command( friend, "move", pos )

(formatting not working)
thanks


Timber guard (what variable)
#5

Have you noticed that this topic is over nine months old? Please keep the dead resting!

Read the FAQ before you post again. You need to learn how to format your code properly. I’ve done it for you this time, but I won’t always be here.

Line 4: self.findNearest( golds )? There isn’t a variable named golds.


Timber guard (what variable)
#6

sorry and thanks 'll read the FAQ