fablefe 发表于 2018-8-4 13:57:15

python基础-函数(一)--python3

  >> fun1('q')
  Traceback (most recent call last):
  File &quot;<pyshell#7>&quot;, line 1, in <module>
  fun1('q')
  TypeError: fun1() takes 0 positional arguments but 1 was given
  >> fun1()
  不能传参数
  #2.必备参数
  def fun2(a):
  print('必须传参数:',a)
  >> fun2(2)
  必须传参数: 2
  #3.默认参数   参数可传也可不传
  def fun3(b=2):
  print('默认参数:',b)
  >> fun3()
  默认参数: 2
  >> fun3(4)
  默认参数: 4
  >> fun3(b=10)
  默认参数: 10
  ##4.可选参数   可传0-多个,包装成元祖
  def fun4(arg):
  print('可以穿0个到多个',arg)
  >> fun4()      #返回一个空元祖
  可以穿0个到多个 ()
  >> fun4(1)       #返回一个元祖
  可以穿0个到多个 (1,)
  >> fun4(2,3)
  可以穿0个到多个 (2, 3)
  >> fun4(4,5,6,7,8)
  可以穿0个到多个 (4, 5, 6, 7, 8)
  >> fun4()
  可以穿0个到多个 (,)
  >> fun4('sdf')
  可以穿0个到多个 ('sdf',)
  >> fun4({'q':123})
  可以穿0个到多个 ({'q': 123},)
  >> fun4((1,2))
  可以穿0个到多个 ((1, 2),)
  #可选参数,传参时加号,就把里面的壳去掉(解包)
  >> fun4((1,2))
  可以穿0个到多个 (1, 2)
  >> fun4({'q':123})
  可以穿0个到多个 ('q',)
  >> fun4()
  可以穿0个到多个 (1, 2)
  >> fun4('sdf')
  可以穿0个到多个 ('s', 'd', 'f')
  ##5.关键字参数
  def fun5(a,b):      #定义的时候跟必备参数一样
  print(a,b)      #必须放到最后
  >> fun5(a=1,b=2)
  1 2
页: [1]
查看完整版本: python基础-函数(一)--python3