笨办法学python习题21 函数可以返回某些东西

来源:互联网 发布:java中的arrays 编辑:程序博客网 时间:2024/05/16 15:04

我们已经学过用=给变量赋值,这次习题我们将学习用return来将函数的值赋给变量:

代码如下:

#-*-coding:utf-8-*-def add(a, b):#加法函数print"ADDING %d + %d"%(a, b)return a+bdef subtract(a, b):#减法函数print"SUBTRACT %d - %d"%(a, b)return a - bdef multiply(a,b):#乘法函数print"MULTIPLY %d * %d"%(a, b)return a*bdef divide(a, b):#除法函数print"DIVIDE %d / %d"%(a,b)return a/bprint"Let's do some math with just functions!"age = add(30, 5)            #返回20-5给ageheight = subtract(78, 4)    #返回78-4给heightweight = multiply(90, 2)    #返回90*2给weightiq = divide(100, 2)         #返回100/2给divideprint"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?"

运行结果:

 simengred$ python ex21.pyLet's do some math with just functions!ADDING 30 + 5SUBTRACT 78 - 4MULTIPLY 90 * 2DIVIDE 100 / 2Age: 35,Height:74,Weight:180,IQ:50Here is a puzzle.DIVIDE 50 / 2MULTIPLY 180 * 25SUBTRACT 74 - 4500ADDING 35 + -4426That becomes: -4391 Can you do it by hand?
除了return的运用外,在多个函数叠加使用时,运算的顺序为:从内到外

例如:

what = add(age,subtract(height,multiply(weight,divide(iq,2))))
这个函数中,运算顺序是divide-multiply-subtract-add



阅读全文
0 0
原创粉丝点击