1. 参数默认值
#!/usr/bin/python3# functions.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
def main():
testfunc(42,16)
def testfunc(number,another=1,more=2): #若不给值的默认值
print('This is a test function',number,another,more)
#如果你想方法体里什么都不实现 用pass
if __name__ == "__main__": main()
This is a test function 42 16 2
2 可变参数
#!/usr/bin/python3
# functions.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
def main():
testfunc(42,5,6,7,8,9,10)
#可变参数格式 是一个数组
def testfunc(number,another=1,more=2,*args):
print(number,another,more,args)
for n in args:
print (n,end=' ')
if __name__ == "__main__": main()
42 5 6 (7, 8, 9, 10)
7 8 9 10
3.named args
#!/usr/bin/python3
# functions.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
def main():
testfunc(42, 1, 2, 3, 4, 5, 6, 7, 8, 9, one=1, two=2, three=3)
def testfunc(number, another=1, more=2, *args, **kwargs):
print('This is a test function', number, another, more)
# *args as a truple
# *kwargs as dictionary
for n in args:print(n, end=' ')
print()
for k in kwargs:print(k, kwargs[k])
if __name__ == "__main__": main()
This is a test function 42 1 2
3 4 5 6 7 8 9
three 3
two 2
one 1
4.返回值
#!/usr/bin/python3
# functions.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
def main():
for n in testfunc(5):print(n,end=' ')
def testfunc(number):
if number <0:
print('parameter is illegal')
return range(0)
return range(number)
if __name__ == "__main__": main()
0 1 2 3 4
5.生成迭代
一个参数 到几 每次涨一
两个参数 从几到几 每次涨一
3个参数 从几到几 每次涨几
#!/usr/bin/python3
# functions.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
def main():
for n in inclusive_range(3,5,2):print(n,end=' ')
def inclusive_range(*args):
numberarg = len(args)
if numberarg==0:raise TypeError('at least one arg')
elif numberarg==1:
start=0
step=1
stop=args[0]
elif numberarg==2:
(start,stop)=args
step=1
elif numberarg==3:
(start,stop,step)=args
else :raise TypeError('at most three args')
i=start
while i <= stop:
yield i
i+=step
if __name__ == "__main__": main()
3 5