2012-03-13 121 views
0
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?" 

的註釋線下做的第一件事是調用函數divide。我很好奇,爲什麼這樣做?是因爲python實際上理解操作的順序,還是因爲這條線有鏈條結構?爲什麼這行代碼以這種方式工作?

回答

2

想一想。當你不知道subtract()的結果是什麼時,你將如何撥打add()?如果您不知道multiply()的結果是什麼,您將如何撥打subtract()?最後,如果您不知道divide()的結果是什麼,您將如何撥打multiply()

與代數符號一樣,圓括號內的操作首先完成。如果括號內有圓括號,則最內層的操作首先完成。它不能以其他方式工作。

3

在調用函數之前,Python必須評估傳遞給該函數的參數。 (沒有其他選擇 - 參數的值只有在已知的情況下才能通過)。

以遞歸方式應用此原則,唯一的選擇是首先調用divide() - 在此之前,參數無其他參數功能是已知的。

0

Python(以及任何具有函數的語言)都理解函數調用的操作順序。

如果你有一些函數f(),G()和h(),像

f(g(h())) 

需求,以調用克()H()結果的聲明,並將結果在調用f()之前需要g(h())。

1

答案很簡單 - 在調用之前,所有函數都必須進行評估才能正常工作。

在這種情況下:

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

要計算你必須計算age價值和

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

要計算你必須計算height值的subtract(...)值的add(...)價值

multiply(weight, divide(iq, 2)) 

等。

相關問題