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?