Variable in example code isn't declared (cubic minefield)


#1

In cubic minefield in Sarven desert, the intial sample code looks like this:


# Laufe durch das Minenfeld

# Diese Funktion gibt "number" multipliziert mit "times" zurück
def mult(number, times):
    total = 0
    while times > 0:
        total += number
        times -= 1
    return total

I don’t understand this, because the variable “times” has no initially declared value - therefore it can’t be used for calculating times - 1

I believe the below function power(number, exponent) works because the initial values for variables number and exponents are handed to it by the while True loop at the bottom:

# Diese Funktion berechnet die Potenz "number `hoch` exponent".
def power(number, exponent):
    total = 1
    # Vervollständige die Funktion.
def power(number, exponent):
    total = 1
    # Vervollständige die Funktion.
    while exponent > 0:
        total *= number
        exponent -= 1
    return total

# Ändere den folgenden Code nicht
# Die Koeffizienten für die Gleichung findest du auf dem Turm
tower = hero.findFriends()[0]
a = tower.a
b = tower.b
c = tower.c
d = tower.d
x = hero.pos.x

while True:
    # Benutze eine kubische Gleichung, um den Pfad zu finden
    y = a * power(x, 3) + b * power(x, 2) + c * power(x, 1) + d * power(x, 0)
    hero.moveXY(x, y)
    x = x + 5

…Whereas the first function mult(number, times) couldn’t work if it where run, but it’s never actually called upon in this program. Is that correct?


#2

Your right about the power(number, exponent) function, in that it only works if it has numbers put into it in the while loop at the bottom, like power(x, 2) , but you could also do this with the mult(number, times) function. For example, in the bottom while loop, you could give it the values x and 2: mult(x, 2), and it would calculate the total from those two values. Because it is a function, you don’t have to say what the value of times is, because when you put it in a while loop, you give it the variable for times, and any use of times in the function will then be the variable you give it. So, the mult(number, times) would work, as long as you give it a value for times, like mult(x, 2). Hope this makes sense.