函数的定义

来源:互联网 发布:windows ce 6.0 编辑:程序博客网 时间:2024/05/22 07:05

1.函数的一般形式

定义一个函数需要以下规则:

函数代码块以 def 关键词开头,后接函数标识符名称和圆括号()

任何传入参数和自变量必须放在圆括号中间,圆括号中间可以用于自定义参数。

函数的第一行语句可以选择性的使用文档字符串-用于存放函数说明

函数内容以冒号起始,并且缩进

return[表达式] 表示函数结束,不带表达式的return,返回None

创建一个函数:

def fun(x,y):    print ('x = {0}'.format(x))    print ('y = {0}'.format(y))    return x+yx =1y =3z = fun(x,y)print z
返回为:

x = 1y = 34


tips:

def是函数的关键字,函数的格式

def 后面就是函数名字,这个可以自定义

括号里面传递的是函数的参数,改参数在函数中都可以使用

return 是表带当我们调用函数的时候返回的结果。



2.函数的各种类型参数

1.实例1:

def fun1(a,b=0):    print a    print bfun1(1)
结果为:

10
如果把fun1(1)改为fun1(1,2),结果为:

12
fun1(a,b=0)其实是给b 设置了一个默认参数,如果没有给b设置参数,b就是0,设置了参数,优先使用设置的实参。


2.参数为tuple, man(m,*args)

def fun2(a,b,*c):    print a    print b    print 'leng c is %d' % len(c)    print cfun2(1,2,3,4,5,6)
结果为:

12leng c is 4(3, 4, 5, 6)
也可以这样写

def fun2(a,b,*c):    print a    print b    print 'leng c is %d' % len(c)    print c#fun2(1,2,3,4,5,6)tub = ('hello','world')fun2(1,2,*tub)                        #用星号


3.参数为字典,man(m,**args) 两个星号

def fun3(a,**b):    print(a)    print(b)    for x in b:        print x + ':' + str(b[x])fun3(100,x='hello',y='你好')
结果为:

100{'y': '\xe4\xbd\xa0\xe5\xa5\xbd', 'x': 'hello'}y:你好x:hello
也可以用**去写

n3(a,**b):    print(a)    print(b)    for x in b:        print x + ':' + str(b[x])fun3(100,x='hello',y='你好')args = {'1':'abc','b':'hello'}fun3(100,**args)
结果为:

100{'y': '\xe4\xbd\xa0\xe5\xa5\xbd', 'x': 'hello'}y:你好x:hello100{'1': 'abc', 'b': 'hello'}1:abcb:hello








原创粉丝点击