Learn Python The Hard Way学习(21) - 函数可以返回信息


我们可以使用=号给变量赋字符串或者数字,现在我们可以用=给变量赋函数中return回来的值,这里有一个要注意的地方,但是我们还是写把程序写出来吧:
[python] 
def add(a, b): 
    print "ADDING %d + %d" % (a, b) 
    return a + b 
 
 
def subtract(a, b): 
    print "SUBTARCTING %d - %d" % (a, b) 
    return a - b 
 
 
def multiply(a, b): 
    print "MULTIPLING %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 credit, 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?" 


现在我们可以用自己的函数进行加减乘除计算了,重要的是,在函数结尾我们看到了return语句,下面我们分析一下:
我们的方法有两个参数:a和b。
函数第一行打印了这个函数是做什么的。
我们用return告诉python,我们要返回a+b的结果。
python计算a+b的结果,然后返回值给一个变量。
这里我们一步一步的分析程序的运行,加深理解;在加分练习中有更酷的东西。

运行结果
Let's do some math with just functions!
ADDING 30 + 5
SUBTARCTING 78 - 4
MULTIPLING 90 * 2
DIVIDING 100 / 2
Age: 35, Height: 74, Weight: 180, IQ: 50
Here is a puzzle.
DIVIDING 50 / 2
MULTIPLING 180 * 25
SUBTARCTING 74 - 4500
ADDING 35 + -4426
That becomes: -4391 Can you do it by hand?

加分练习
1. 如果你还确定return的用法,那多做一些练习,return可以返回任何=号右边的东西。

2. 在程序的最后,我们使用函数返回的值做另外一个函数的参数。这个使用函数组成的链式公式看上去有写奇怪,但是可以运行出结果。看看你能不能用正常的公式实现上面那个操作。

3. 一旦你了解了上面的谜题,你可以试着修改一下函数,让他计算出不同的结果。

4. 最后,颠倒过来做一次,写出公式然后计算结果。


作者:lixiang0522

相关内容

    暂无相关文章

评论关闭