复习PythonDay20
发布日期:2021-07-01 03:02:55 浏览次数:2 分类:技术文章

本文共 1377 字,大约阅读时间需要 4 分钟。

复习Python第二十天

习题 21: 函数可以返回东西

# 定义加法函数def add(a,b):    print "ADDING %d + %d" %(a,b)    return a+b# 定义减法函数def subtract(a,b):    print "SUBTRACTING %d - %d" %(a,b)    return a - b# 定义乘法函数def multiply(a,b):    print "MULTPLYING %d * %d" %(a,b)    return a * b# 定义除法函数def divide(a,b):    print "DIVIDING %d / %d" %(a,b)    return a/bprint "Let's do some math with just functions!"# 年龄,调用函数add,打印一条信息,同时返回a+b的值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?"

函数调用嵌套图:

运行结果:

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

现在我们创建了我们自己的加减乘除数学函数: add, subtract, multiply, 以 及 divide。重要的是函数的最后一行,例如 add 的最后一行是 return a+b。意指返回a+b的值,并将赋值给一个变量。

注:任何可以放在 = 右边的东西都可以作为一个函数的返回值。

在这一节中我觉得最重要的是,我们在函数调用的时候,既能执行函数功能,又能同时返回(return)值创建变量。

加分习题

用正常的方法实现和这个表达式一样的功能。

a = divide(iq, 2)b = multiply(weight, a)c = subtract(height, b)d = add(age, c)

就把它拆解就可以了。

其他习题没什么好做的。

转载地址:https://memcpy0.blog.csdn.net/article/details/79821500 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:一本python学习的好书
下一篇:复习Python的Day19

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2024年04月08日 14时57分26秒