“Function” 简述
本节开始学习 Function 概念。那么,Function 是干嘛的? Zed 的观点, Function 做三件事:
- 如同使用变量命名字符串和数字一样, 函数命名一段代码。
- 如同脚本通过 argv 获取参数一样,Function 也做同样的事。
- 把 1 和 2 联合使用,定制自己的 “小脚本” 或 “微命令”。 在 Python 中,创建函数要用到 def。
示例代码 Ex18:
|
|
代码运行结果:
小结
- Function Checklist
- Did you start your function definition with def ?
- Does your function name have only characters and _ (underscore) characters?
- Did you put an open parenthesis ( right after function name ?
- Did you put your arguments after the parenthesis ( separated by commas ?
- Did you make each argument unique(meaning no duplicated names) ?
- Did you put a close parenthesis and a colon ): after the arguments?
- Did you indent all lines of code you want in the function four spaces? No more, no less.
- Did you “end” your finction by going back to writing with no indent ( dedenting we call it)?
- Call Function Checklist
- Did you call/use/run this function by typing its name ?
- Did you put ( character after the name to run it ?
- Did you put the values you want into the parenthesis separated by commas?
- Did you end the function call with ) characte ?