[Sand Snakes] Explanation on Python indentation help needed

Hello! Love CC so far, had a few stuff I could get by just using Google for explanation, but here’s something I don’t understand:

while True:
    coins = hero.findItems()
    coinIndex = 0
    nearest = None
    nearestDistance = 9999
    
    # Loop through all the coins to find the nearest one.
    while coinIndex < len(coins):
        coin = coins[coinIndex]
        coinIndex += 1
        distance = hero.distanceTo(coin)
        # If this coin's distance is less than the nearestDistance
        if distance < nearestDistance:
            # Set nearest to coin
            nearest = coin
            # Set nearestDistance to distance
            nearestDistance = distance
            
    # If there's a nearest coin, move to its position. You'll need moveXY so you don't cut corners and hit a trap.
            if nearest:
                hero.moveXY(nearest.pos.x, nearest.pos.y)

Just for info, I passed the level after fixing the last line’s indentation (the code above is prior to fixing). I don’t understand why is it that I must put that last if statement indented to the while loop, and not indented within the previous if statement? (My understanding for putting this if statement in the previous if statement is that the code can only check if there’s a nearest coin only if the previous if statement’s criteria is met)

I apologize if this question is too vague/intuitive, but any help or explanation would be really appreciated!

Hi @yingyiying, welcome to the forum.

You’re correct that that code will only run if

is True, but remember that when you’re in the middle of checking all the coins, the current coin may be the current “nearest”, but there may be another coin (that you haven’t checked yet ) which is nearer. Therefore, if you move for that coin, you will not be going in the right direction. Also this will happen for the first coin you check, because nearestDistance is set to a number higher than any distance to any of the coins on the level could be, that means you’ll move for the first coin you check every time.
This is why you have to wait until the while loop is finished before you could move to the nearest (which at this point will actually be the nearest).
Danny

2 Likes

I see, thank you so much! Coding is pretty intuitive, I’m glad I got a chance to start off here!

1 Like

My pleasure. :grin: (I’ll close this topic now it’s solved).
Danny

1 Like