Ex18 Names,Variables,Code,Functions

“Function” 简述

本节开始学习 Function 概念。那么,Function 是干嘛的? Zed 的观点, Function 做三件事:

  1. 如同使用变量命名字符串和数字一样, 函数命名一段代码。
  2. 如同脚本通过 argv 获取参数一样,Function 也做同样的事。
  3. 把 1 和 2 联合使用,定制自己的 “小脚本” 或 “微命令”。 在 Python 中,创建函数要用到 def

示例代码 Ex18:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# This one is like your scripts with argv
def print_two(*args):
    arg1, arg2 = args
    print "arg1: %r, arg2: %r." % (arg1, arg2)
# OK, that *args is actually pointless, we can just do this.
def print_two_again(arg1, arg2):
    print "arg1: %r, arg2: %r." % (arg1, arg2)
# This just takes one argument
def print_one(arg1):
    print "arg1: %r" % arg1
# This one takes no arguments
def print_none():
    print "I got nothing'."
print_two("Zed","Shaw")
print_two_again("Zed","Shaw")
print_one("First!")
print_none()

代码运行结果:

小结

  • Function Checklist
    1. Did you start your function definition with def ?
    2. Does your function name have only characters and _ (underscore) characters?
    3. Did you put an open parenthesis ( right after function name ?
    4. Did you put your arguments after the parenthesis ( separated by commas ?
    5. Did you make each argument unique(meaning no duplicated names) ?
    6. Did you put a close parenthesis and a colon ): after the arguments?
    7. Did you indent all lines of code you want in the function four spaces? No more, no less.
    8. Did you “end” your finction by going back to writing with no indent ( dedenting we call it)?
  • Call Function Checklist
    1. Did you call/use/run this function by typing its name ?
    2. Did you put ( character after the name to run it ?
    3. Did you put the values you want into the parenthesis separated by commas?
    4. Did you end the function call with ) characte ?
Licensed under CC BY-NC-SA 4.0
使用 Hugo 构建
主题 StackJimmy 设计