python中的函数1

来源:互联网 发布:mysql offset 编辑:程序博客网 时间:2024/06/10 17:44

1.定义函数的时候可以在传参数的时候设置一个默认值,不过只能在最后的一个参数设置默认值,比如:

def say(what,time=1):
print(what*time)
say('hi')

say('hi',3)


2.函数中的可变参数,*param 代表参数是个元组,**param代表参数是个字典

>>> def total(a=5,*numbers,**people):
...     print('a',a)
...
...     for single_item in numbers:
...         print('single_item',single_item)
...
...     for name,age in people.items():
...         print(name,age)
...
>>> print(total(10,1,2,3,jack=23,john=25,Inge=26))

('a', 10)
('single_item', 1)
('single_item', 2)
('single_item', 3)
('Inge', 26)
('john', 25)
('jack', 23)
None


3.python中有一个文档字符串的功能,通过调用 __doc__ 可以将函数中的说明打印出来,比如一下有个找出个函数

def print_max(x,y):
''' this function will find the max num 
print  maximum of the two num
the two number must be integer'''
x = int(x)
y = int(y)


if(x>y):
print('x is max')
else:
print('y is max')


print_max(3,5)
print(print_max.__doc__)

最终结果将打印以下内容:

y is max
 this function will find the max num 
print  maximum of the two num
the two number must be integer




4.format方法

format放在字符串之后,将方法中的参数替换到字符串中的参数位置,比如

>>> name='uncle_king'
>>> what='python'
>>> print('{0} study {1}'.format(name,what))
uncle_king study python

其中{0}对应第一个变量name,{1}对应第二个变量 what,不过{}里面的数字可以省略:

>>> print('{} study {}'.format(name,what))
uncle_king study python



原创粉丝点击