函数可以做三件事:
1、它们给代码片段命名,就跟“变量”给字符串和数字命名一样。
2、它们可以接受参数,就跟你的脚本接受 argv 一样。
3、通过使用 #1 和 #2,它们可以让你创建“微型脚本”或者“小命令”。
书中代码:
# 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 nothin'."
print_two("Zed","Shaw")
print_two_again("Zed","Shaw")
print_one("First!")
print_none()
输出结果: