《笨办法学Python》 第21课手记
2016-01-24 21:24
615 查看
《笨办法学Python》 第21课手记
本节课介绍函数和返回值,出现了函数嵌套,即函数的返回值可以不经赋值而直接做函数参数使用。原代码如下:
def add(a, b): #定义一个函数,下同,函数的运算分别加、减、乘和除。 print "ADDING %d + %d" %(a, b) return a + b #函数返回a+b的值,下同,对应各自的运算 def subtract(a, b): print "SUBTRACTING %d - %d" %(a, b) return a - b def multiply(a, b): print "MULTIPLYING %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 anyway. print "Here is a puzzle." what = add(age, subtract(height, multiply(weight, divide(iq, 2)))) #嵌套函数,4个函数3层嵌套 print "That's becomes:", what, "Can you do it by hand?"#请留心这种输出格式,两个字符串之间加了变量
结果如下:
本节课涉及的知识
这节课蛮简单,请注意常见问题解答。函数的嵌套是非常常用的用法
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
4个紫色的字符串代表四个函数,其中divide的结果做multiply的参数,mutiply的结果又做subtract的参数,subtract的结果又做add的参数,所以是3层嵌套。当然嵌套不仅有这种用法,还有其他用法,比如循环嵌套。以后遇到具体例子再讲,请先将这节课充分理解。
相关文章推荐
- Python 2015 年最热门的 10 篇技术文章
- Python matplotlib
- 在python调用opencv库,使用pycharm环境
- windows 下安装pip
- Windows 命令行下解决python utf-8中文输出的终极解决方案!
- python
- sphinx-for-python
- Python中通过多个字符分割(split)字符串的方法
- python 之自定义函数
- Python3中重新加载一个新的更正的代码
- Python爬虫实战(3):计算大学本学期绩点
- Python爬虫实战(2):百度贴吧帖子
- Python爬虫实战(1):爬取糗事百科段子
- Python爬虫入门(7):正则表达式
- Python爬虫入门(6):Cookie的使用
- Python爬虫入门(5):URLError异常处理
- Python爬虫入门(4):Urllib库的高级用法
- Python爬虫入门(3):Urllib库的基本使用
- Python爬虫入门(2):爬虫基础了解
- 对于python,一切事物都是对象,对象基于类创建