💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 习题 21: 函数可以返回东西 你已经学过使用 = 给变量命名,以及将变量定义为某个数字或者字符串。接下来我们将让你见证更多奇迹。我们要演示给你的是如何使用 = 以及一个新的 Python 词汇return 来将变量设置为“一个函数的值”。有一点你需要及其注意,不过我们暂且不讲,先撰写下面的脚本吧: <table class="highlighttable"><tbody><tr><td class="linenos"> <div class="linenodiv"> <pre> 1&#13; 2&#13; 3&#13; 4&#13; 5&#13; 6&#13; 7&#13; 8&#13; 9&#13; 10&#13; 11&#13; 12&#13; 13&#13; 14&#13; 15&#13; 16&#13; 17&#13; 18&#13; 19&#13; 20&#13; 21&#13; 22&#13; 23&#13; 24&#13; 25&#13; 26&#13; 27&#13; 28&#13; 29&#13; 30&#13; 31&#13; 32&#13; 33</pre> </div> </td> <td class="code"> <div class="highlight"> <pre>def add(a, b):&#13; print "ADDING %d + %d" % (a, b)&#13; return a + b&#13; &#13; def subtract(a, b):&#13; print "SUBTRACTING %d - %d" % (a, b)&#13; return a - b&#13; &#13; def multiply(a, b):&#13; print "MULTIPLYING %d * %d" % (a, b)&#13; return a * b&#13; &#13; def divide(a, b):&#13; print "DIVIDING %d / %d" % (a, b)&#13; return a / b&#13; &#13; &#13; print "Let's do some math with just functions!"&#13; &#13; age = add(30, 5)&#13; height = subtract(78, 4)&#13; weight = multiply(90, 2)&#13; iq = divide(100, 2)&#13; &#13; print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)&#13; &#13; &#13; # A puzzle for the extra credit, type it in anyway.&#13; print "Here is a puzzle."&#13; &#13; what = add(age, subtract(height, multiply(weight, divide(iq, 2))))&#13; &#13; print "That becomes: ", what, "Can you do it by hand?"&#13; </pre> </div> </td> </tr></tbody></table> 现在我们创建了我们自己的加减乘除数学函数: add, subtract, multiply, 以及 divide。重要的是函数的最后一行,例如 add 的最后一行是 returna+b,它实现的功能是这样的: 1. 我们调用函数时使用了两个参数: a 和 b 。 1. 我们打印出这个函数的功能,这里就是计算加法(adding) 1. 接下来我们告诉 Python 让它做某个回传的动作:我们将 a+b 的值返回(return)。或者你可以这么说:“我将 a 和 b 加起来,再把结果返回。” 1. Python 将两个数字相加,然后当函数结束的时候,它就可以将 a+b 的结果赋予一个变量。 和本书里的很多其他东西一样,你要慢慢消化这些内容,一步一步执行下去,追踪一下究竟发生了什么。为了帮助你理解,本节的加分习题将让你解决一个迷题,并且让你学到点比较酷的东西。 ### 你应该看到的结果 ~~~ $ python ex21.py Let's do some math with just functions! ADDING 30 + 5 SUBTRACTING 78 - 4 MULTIPLYING 90 * 2 DIVIDING 100 / 2 Age: 35, Height: 74, Weight: 180, IQ: 50 Here is a puzzle. DIVIDING 50 / 2 MULTIPLYING 180 * 25 SUBTRACTING 74 - 4500 ADDING 35 + -4426 That becomes: -4391 Can you do it by hand? $ ~~~ ### 加分习题 1. 如果你不是很确定 return 的功能,试着自己写几个函数出来,让它们返回一些值。你可以将任何可以放在 = 右边的东西作为一个函数的返回值。 1. 这个脚本的结尾是一个迷题。我将一个函数的返回值用作了另外一个函数的参数。我将它们链接到了一起,就跟写数学等式一样。这样可能有些难读,不过运行一下你就知道结果了。接下来,你需要试试看能不能用正常的方法实现和这个表达式一样的功能。 1. 一旦你解决了这个迷题,试着修改一下函数里的某些部分,然后看会有什么样的结果。你可以有目的地修改它,让它输出另外一个值。 1. 最后,颠倒过来做一次。写一个简单的等式,使用一样的函数来计算它。 这个习题可能会让你有些头大,不过还是慢慢来,把它当做一个游戏,解决这样的迷题正是编程的乐趣之一。后面你还会看到类似的小谜题。