首页 > 编程语言 > 详细

Python函数

时间:2016-10-13 02:41:29      阅读:160      评论:0      收藏:0      [点我收藏+]
        

函数

      def  函数名(形参):
              函数体
              返回值

函数参数:

  1 普通参数 (严格按照指定顺序,将实际参数值赋值给形参)
  2 默认参数(必须放在参数列表的最后)
  3 指定参数(将实际参数赋值给指定的参数)
  4  * (*args,元组参数)
  5 **(**dicArgs,字典参数)
  6 万能参数  (*args,**kwargs)

2 默认参数

  1. def f1(text,num=999):
  2. print(text,num)
  3. f1("Hello")
  4. Hello 999

3 指定参数

  1. def f2(ip,port):
  2. print("%s:%d"%(ip,port))
  3. f2(ip="192.168.1.1",port=8080)
  4. 192.168.1.1:8080

  4  *  (元组参数)

  1. def  f1(*args)def f1(*args):
  2. print(args)
  3. f1(11,22,33,‘abc‘)
  1. def f1(*args):
  2. print(‘args-->‘,args)
  3. tuple=(11,22,33)
  4. f1(tuple,999)
  5. f1(*tuple)
  6. args--> ((11, 22, 33), 999)
  7. args--> (11, 22, 33)

5 **(字典参数)

    
  1. def f1(**dicArgs):
  2. print(‘dicArgs-->‘,dicArgs,type(dicArgs))
  3. dic={‘name‘:‘lucy‘,‘age‘:18,‘sex‘:‘female‘}
  4. f1(**dic)
  5. dicArgs--> {‘name‘: ‘lucy‘, ‘sex‘: ‘female‘, ‘age‘: 18} <class ‘dict‘>

  6 万能参数

  1. def f1(*args,**kwargs):
  2. print(args)
  3. print(kwargs)
  4. f1(11,22,33,44,k1=‘a‘,k2=‘b‘,k3=‘c‘)
  5. ------------
  6. (11, 22, 33, 44)
  7. {‘k3‘: ‘c‘, ‘k2‘: ‘b‘, ‘k1‘: ‘a‘}
  1. #format----*args,**wkargs
  2. s1="I am {0},age{1}".format("tan",22)
  3. print(s1)
  4. s2="I am {0},age{1}".format(*["tan",32])
  5. print(s2)
  6. s3="I am {name},age{age}".format(name=‘tan‘,age=19)
  7. print(s3)
  8. dic={‘name‘:‘alex‘,‘age‘:20}
  9. s4="I am {name},age{age}".format(**dic)
  10. print(s4)
  11. I am tan,age22
  12. I am tan,age32
  13. I am tan,age19
  14. I am alex,age20







Python函数

原文:http://www.cnblogs.com/fftan/p/5954879.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!