发布时间:2017-11-13 20:53:55编辑:Run阅读(5938)
使用return来将变量设置为'一个函数的值'
代码如下
# coding: utf-8
__author__ = 'www.py3study.com'
def add(a, b):
print("ADDING {} + {}".format(a, b))
return a + b
def subtract(a, b):
print("SUBTRACTING {} - {}".format(a, b))
return a - b
def multiply(a, b):
print("MULTIPLY {} * {}".format(a, b))
return a * b
def divide(a, b):
print("DIVIDE {} / {}".format(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:{}, Height:{}, Weight:{}, IQ:{}".format(age, height, weight, iq))
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 ?")注释:上面例子,创建了加减乘除数学函数:add,subtract,multiply,以及divide 重要的是函数的最后一行,例如add的最后一
行是return a + b,它的实现功能是这样的:
1.调用函数是使用了两个参数: a 和 b
2.打印出这个函数的功能,这里就是计算加法
3.接下来告诉python让它做某个回传的动作:我们将a + b 的值返回(return),或者可以理解为把a 和 b加起来,再把结果返回
4.Python将两个数字相加,然后当函数结束的时候,它就可以将a + b 的结果赋予一个变量
应该看到的结果

上一篇: 习题20:函数和文件
下一篇: 习题22:更多的练习
51225
50650
41264
38077
32544
29448
28309
23169
23130
21463
1527°
2238°
1864°
1802°
2100°
1853°
2536°
4258°
4112°
2935°