python shape function of four parameters

In python, the physical parameters of the function parameters and arguments two kinds, the parameter can be divided into: a position parameter, default parameter, the variable parameter, the parameter keyword four.

1. Location parameter

Parameter argument must be consistent and

def getinfo(name,age):
    print('姓名:',name,'年龄:',age)

getinfo('westos',12)
getinfo(12,'westos')
getinfo(age=12,name='westos')

Output:
Here Insert Picture Description

2. The default parameters

And parameter arguments can be different, if the value is not passed, then the default value

def mypow(x,y=2):	# y的默认值为2,不添加参数y时默认以y=2计算
    print(x ** y)
mypow(2,3)
mypow(2)

Output:
Here Insert Picture Description

3. The variable parameter (args)

* args: variable parameter, a plurality of parameters may be received
args: data type is a tuple

def mysum(*args):
    print(*args)
    print(args)
    sum  = 0
    for item in args:
        sum += item
    print(sum)

mysum(1,2,3,4,5,6,7,8)

Output:
Here Insert Picture Description
Unpack parameters: added before the parameter name *

ef mysum(*args):
    print(*args)
    print(args)
    sum = 0
    for item in args:
        sum += item
    print(sum)

nums1 = [1, 2, 3]
nums2 = (1, 2, 3)
nums3 = {1, 2, 3}
# 参数的解包:在参数名前加*
mysum(*nums1)
mysum(*nums2)
mysum(*nums3)

Output:
Here Insert Picture Description

4. keyword arguments

def getinfo(name,age,**b):		# **b是一个字典,可以传递任意多个key-value
    print(name)
    print(age)
    print(b)

d = dict(a=1,b=2)
print(d)
print(*d)
getinfo('westos',12,**d)

Output:
Here Insert Picture Description

def getinfo(name,age,**b):		
    print(name)
    print(age)
    print(b)

getinfo('tom',19,hobbies=['code','running'],gender='female')

Output:
Here Insert Picture Description

Published 60 original articles · won praise 6 · views 1360

Guess you like

Origin blog.csdn.net/weixin_45775963/article/details/103696945