1. 程式人生 > >Python_函數_參數

Python_函數_參數

返回 tro python解釋器 技術 順序執行 傳參 result png 插入

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

Python_函數_參數