Defining variables in Python


#1

Why does this code work?

def sumCoinValues(coins):
    coinIndex = 0
    totalValue = 0
    # Durchlaufe alle Münzen.
    while coinIndex < len(coins):
        totalValue += coins[coinIndex].value
        coinIndex += 1
    return totalValue

(it’s from Wishing Well)

What I’m struggling to understand here is that coins is not defined anywhere - neither inside the function sumCoinValues(coins) nor outside. They way I see it, this should throw an error, like “cannot read property of undefined” or similar. At the very least, it has to have a data type (which is normal set by defining the function), right?

In a Python learning app’s discussion forum, some user claimed that Python doesn’t need you to declare variables. I vigorously objected and said that it certainly does require it, but you could declare a variable along with defining a function.
These may be the case here - coins is the parameter passed to sumCoinValues(coins). I also saw someone calling that a “virtual variable” - a variable that is only used inside a function and isn’t valid outside it.
The way I nunderstan it, the i in a for i in -loop is exactly one such virtual variable.
Am I right so far?

Anyways, in this here sumCoinValues(coins), coins is called with
while coinIndex < len(coins):
but there is nothing passing a value to it. The length of coins cannot be determined because there’s nothing in it (not even None)!
Why/how does it work?


#2

If you look at the code for wishing well:

# You need exactly 104 gold. 

less = "Nimis"
more = "Non satis"
requiredGold = 104

# This function calculates the sum of all coin values.
def sumCoinValues(coins):
    coinIndex = 0
    totalValue = 0
    # Iterate all coins.
    while coinIndex < len(coins):
        totalValue += coins[coinIndex].value
        coinIndex += 1
    return totalValue

def collectAllCoins():
    item = hero.findNearest(hero.findItems())
    while item:
        hero.moveXY(item.pos.x, item.pos.y)
        item = hero.findNearest(hero.findItems())

while True:
    items = hero.findItems()
    # Get the total value of coins.
    goldAmount = sumCoinValues(items)

(I won’t contain the rest of the code because that would be the solution.)
In this line: goldAmount = sumCoinValues(items) you can see that in the brackets of the sumCoinValues function there is this: items. Items is a defined variable (items = hero.findItems()) so when the program runs the code it fills in all the (coins) in the sumCoinValues function with the defined variable: item. If instead of item you put in a non defined variable for example:

while True
    sumCoinValues(haralilke)

it would create an error: Fix your code, line 26: reference error: haralilke is not defined.
the reason this error doesn’t pop up when it’s in the function is that it isn’t being run by the computer so it can’t pick up the error.
Hope this helps.