你已经学过使用 = 给变量命名,以及将变量定义为某个数字或者字符串。接下来我们将让你见证更多奇迹。我们要演示给你的是如何使用 = 以及一个新的 Python 词汇return 来将变量设置为“一个函数的值”。有一点你需要及其注意,不过我们暂且不讲,先撰写下面的脚本吧:
1 def add(a, b): 2 print "ADDING %d + %d" % (a, b) 3 return a + b 4 5 def subtract(a, b): 6 print "SUBTRACTING %d - %d" % (a, b) 7 return a - b 8 9 def multiply(a, b): 10 print "MULTIPLYING %d * %d" % (a, b) 11 return a * b 12 13 def divide(a, b): 14 print "DIVIDING %d / %d" % (a, b) 15 return a / b 16 17 18 print "Let's do some math with just functions!" 19 20 age = add(30, 5) 21 height = subtract(78, 4) 22 weight = multiply(90, 2) 23 iq = divide(100, 2) 24 25 print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq) 26 27 28 # A puzzle for the extra credit, type it in anyway. 29 print "Here is a puzzle." 30 31 what = add(age, subtract(height, multiply(weight, divide(iq, 2)))) 32 33 print "That becomes: ", what, "Can you do it by hand?"