1.创建和调用函数
1.1
def 函数名():
内容
>>> def fun():
print("abc")
>>> fun()
abc
1.2
带参数的函数
>>> def func(a,b):
print(a+b)
>>> func(2,3)
5
>>>
1.3
带返回值的函数
>>> def add(a,b):
return a+b
>>> sum=add(3,4)
>>> sum
7
1.4
函数文档,在函数开头三个引号括起来的字,类似注释,但是会作为函数的一部分存储起来,且内容可以通过特殊属性__doc__获取,也可以用helep()函数来查看函数文档
>>> def exchangerate(dollar):
"""美元->人民币
汇率暂定为6.5
"""
return dollar*6.5
>>> exchangerate(10)
65.0
>>> exchangerate.__doc__
'美元->人民币\n\t汇率暂定为6.5\n\t'
>>> help(exchangerate) #help()函数查看函数文档
Help on function exchangerate in module __main__:
exchangerate(dollar)
美元->人民币
汇率暂定为6.5
1.5
关键字参数,普通参数是位置参数,当参数过多时,位置会搞混,所以这时关键字参数更加方便
>>> def name(a,b):
return a+'->'+b
>>> a=name(a='小明',b='小红')
>>> a
'小明->小红'
>>> b=name(b='小红',a='小明')
>>> b
'小明->小红'
” a=‘小明’ “就是关键字参数
1.6
默认参数,
>>> def addc(a=0,b=0):
return a+b
>>> c=addc()
>>> c
0
>>> c=addc(4)
>>>
>>> c
4
1.7
收集参数,当参数个数不知道时,可以在参数前面加个*,
>>> def test(*a):
print("有%d个参数"%len(a))
print("第二个参数是",a[1])
print(a)
>>> test(1,2,3,4,5,6,7)
有7个参数
第二个参数是 2
(1, 2, 3, 4, 5, 6, 7)
相当于把标志为收集参数的参数打包为元组,如果在收集参数后面还有其他指定参数,则需要用关键字参数来指定,否则都列入收集参数中(建议使用默认参数)
>>> def tes(*a,b):
print(a)
print(b)
>>> tes(1,2,3,4,5,b=123)
(1, 2, 3, 4, 5)
123
*可以打包也可以解包,将列表传入收集参数时,直接传入列表名会出错,需要在列表名前加一个 *来解包
>>> a=[1,2,3,4,5,6]
>>> tes(*a,b=123)
(1, 2, 3, 4, 5, 6)
123
repr函数
repr() 函数将对象转化为供解释器读取的形式,返回一个对象的 string 格式。
repr(object)
就是把对象转换为字符串格式的对象
>>>s = 'RUNOOB'
>>> repr(s)
"'RUNOOB'"
>>> dict = {'runoob': 'runoob.com', 'google': 'google.com'};
>>> repr(dict)
"{'google': 'google.com', 'runoob': 'runoob.com'}"