Python Function Defination


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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章