《笨辦法學python》加分習題21——我的答案
阿新 • • 發佈:2019-02-08
這是我自己學習的答案,會盡力寫的比較好。還望大家能夠提出我的不足和錯誤,謝謝!
文中例題:
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)
# A puzzle for the extra cerdit, type it in anyway.
print "Here is a puzzle."
what = add(age, subtract(height,multiply(weight, divide(iq, 2))))
print "That becomes: ", what, "Can you do it by hand?"
執行結果:
習題答案:
1、這裡提個C語言中的左值右值。大概理解就是左值是一個地址,右值是一個數據。
2、
其實就是分解計算了原先what的運算:
原先what的運算:
what = add(age, subtract(height,multiply(weight, divide (iq, 2))))
改為:
temp1 = divide(iq, 2)
temp2 = multiply(weight, temp1)
temp3 = subtract(height, temp2)
what = add(age, temp3)
4、
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
age = 1
height = 1
weight = 4
iq = 4
what = 100
temp3 = subtract(what, age)
temp2 = add(temp3, height)
temp1 = divide(temp2, weight)
temp = multiply(temp1, iq)
print "answer is %d " % temp