0101amt
0101amt

Reputation: 2478

Why does this line of code work in this way?

def add(a, b):
    print "ADDING %d + %d" % (a, b)
    return a + b

def subtract(a, b):
    print "SUBTRACTING %d - %d" % (a, b)
    return a - b

def multiply(a, b):
    print "MULTIPLYING %d * %d" % (a, b)
    return a * b

def divide(a, b):
    print "DIVIDING %d / %d" % (a, b)
    return a / b


print "Let's do some math with just functions!"

age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)

print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)



print "Here is a puzzle."

# why does the line of code below work in this way?
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))

print "That becomes: ", what, "Can you do it by hand?"

The first thing that the line below the comment does is to call the function divide. I'm curious, why does it do that? Is it because python actually understands the order of operations or is it because of the chain structure that this line has?

Upvotes: 0

Views: 379

Answers (4)

kindall
kindall

Reputation: 184091

Think about it. How would you call add() when you don't know what the result of subtract() is? How would you call subtract() if you don't know what the result of multiply() is? Finally, how would you call multiply() if you don't know what the result of divide() is?

As with algebraic notation, operations inside parentheses get done first. If there are parentheses inside parentheses, the innermost operations are done first. It can't work any other way.

Upvotes: 2

Rafał Rawicki
Rafał Rawicki

Reputation: 22690

The answer is simple - all function arguments have to be evaluated before a call to function.

In this case:

what = add(age, subtract(height, multiply(weight, divide(iq, 2))))

To calculate the value of add(...) you have to calculate value of age and

subtract(height, multiply(weight, divide(iq, 2)))

To calculate the value of subtract(...) you have to calculate value of height and

multiply(weight, divide(iq, 2))

and so on.

Upvotes: 1

Jeremy
Jeremy

Reputation: 2956

Python (and any language with functions) understands the order of operations of function calls.

If you have some functions f(), g(), and h(), a statement like

f(g(h()))

Needs the result of h() in order to call g(), and the result of g(h()) is needed before it can call f().

Upvotes: 0

Sven Marnach
Sven Marnach

Reputation: 601451

Before calling a function, Python has to evaluate the parameters passed to that function. (There's no other choice -- the values of the parameters can only be passed in if they are known.)

Applying this principle recursively, the only choice is to first call divide() -- before this, the arguments to no other function are known.

Upvotes: 3

Related Questions