函数做3件事:
- 他们给代码命名,就像给字符串和数字赋给一个变量名。
- 他们接收参数,就像脚本中的argv。
- 使用第一和第二条实现你自己的迷你脚本或者小型方法。
# this one is like your scripts with argv
def print_two(*args) : #给函数定义了一个变量*args
arg1, arg2 = args
print "arg1: %r, arg2: %r" % (arg1, arg2)
def print_two(*args) : #给函数定义了一个变量*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)
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
def print_one(arg1) :
print "arg1: %r" % arg1
# this one takes no arguments
def print_none() :
print "I got nothin'."
def print_none() :
print "I got nothin'."
print_two("Zed","Shaw")
print_two_again("Zed","Shaw")
print_one("First!")
print_none()
总结:
1.用def定义函数
2.定义变量的两种方法
def print_two(*args):
arg1, arg2 = args
arg1, arg2 = args
等价于
def print_two_again(arg1, arg2):
3. def 最后面是 引号!!!