­

Python_函数_参数

  • 2020 年 1 月 19 日
  • 筆記

     def   是函数的关键字,Python解释器一旦执行到def,默认不执行

def li():      n = 8      n +=1      print(n)    li()  li2 = li  li2()

结果:

9  9

return():用于函数返回值,用于中断函数操作

参数可以是数字,字符串,列表,元组,字典

默认参数:默认参数Python规定放在普通参数后面

def li(a1,a2=11)      print(a1,a2)    li(111)  li(111,222)

结果:

111 11  111 222

指定参数:指定后按指定参数的顺序执行

def li(a1,a2)      print(a1,a2)    li(a2=32,a1=8)

结果:

8 32

动态参数

  默认元组: 

def show(*arg):      print(arg,type(arg))    show(33)  show(11,33,66,44,66)

结果:

(33,) <class 'tuple'>  (11, 33, 66, 44, 66) <class 'tuple'>

  默认字典:

def show(**arg):      print(arg, type(arg))    show( n1=123, n2= 'hello',n3=5,)

结果:

{'n1': 123, 'n2': 'hello', 'n3': 5} <class 'dict'>

  默认先插入元组,再插入字典:

def show(*args, **kwargs):      print(args, type(args))      print(kwargs, type(kwargs))    show(11, 22, 44, 55, n1=88, n2='presly')  l = [11, 22, 44, 55,]  d = {'n1': 123, 'n2': 'hello'}  show(l, d)  show(*l,**d)

结果:

(11, 22, 44, 55) <class 'tuple'>  {'n1': 88, 'n2': 'presly'} <class 'dict'>  ([11, 22, 44, 55], {'n1': 123, 'n2': 'hello'}) <class 'tuple'>  {} <class 'dict'>  (11, 22, 44, 55) <class 'tuple'>  {'n1': 123, 'n2': 'hello'} <class 'dict'>

  动态参数实现 字符串格式化:

例:

# s1 = '{0} is {1}'                       # *args的传参  # l = ['Presly', 'lovely']  # # result = s1.format('Presly', 'lovely')  # result = s1.format(*l)  # print(result)  s1 = '{name} is {acter}'             # **kwargs的传参  d = {'name': 'Presly', 'acter': 'lovely'}  result = s1.format(**d)  print(result)

结果:

Presly is lovely