day09 function returns the value of the parameter
A. Functions
1. Function
Function is a function of the package
grammar:
Defined functions:
def function name (parameter): #define
Function body
transfer:
Function name (arguments)
2. The return value return
def func():
print ( 'bajie')
return 'done' # 0. do not write return no return value (get is None), # 1. Write only return, do not write what is returned is returned or None, but also termination functions
print ( 'bajie') # 2 write return value and returns a value, but also termination functions, the latter 'bajie' # 3 may not be printed return multiple return values:.. return value 1, value 2, value 3 (the received tuple)
rst = func()
print(rst)
3. Parameters
Parameter; time information is passed to the function when the function is performed by
Parameter passing: the arguments to the process parameter
def func (tools): # a function definition, which is in the form of variable parameters
print('open %s' % tools)
func ( 'phone') # the function call, actual parameters
Arguments passed by: a position parameter, a keyword parameters, the mixing parameter
def eat(good_food, no_good_food, drink, ice_cream):
print(good_food, no_good_food, drink, ice_cream)
eat('fgood','nfgood','drink','icc') #按顺序传值, 位置参数
eat(ice_cream='fgood',drink='nfgood',good_food='drink',no_good_food='icc') #关键字参数
eat('bajie','ai',ice_cream='shuishui',drink='haha') #混合参数时, 分两部分:先位置, 后关键字
形参的定义方式: 位置参数, 默认值参数, 动态参数
def eat(good_food, no_good_food, drink, ice_cream): #位置参数
print(good_food, no_good_food, drink, ice_cream)
def regist(name, phone, gender='man'): #默认值参数, 默认值参数必须在参数列表的最后
print(name, phone, gender)
regist('bajie', '10089')
动态参数: 位置
def eat(*food): # * 表示接收位置参数的动态传参
print(food) # food 接收到的是一个元组
print(type(food))
eat('bajie','悟空','大唐')
eat() #可以没有, 是空元组
位置与动态位置的顺序
def eat(name, *food): #位置参数, 和动态位置参数可以共存, 顺序: 先位置, 后动态位置
print("%s want to eat %s" % (name, food))
eat('bajie', 'a','b','c')
动态参数: 关键字
def eat(**food): # ** 表示的是关键字的动态传参
print(food) # food接收到的是(不完全)字典
print(type(food))
eat(name = 'bajie', age = '100') # key 是变量(要遵守变量的命名规则), (数字不行, 字符串不行)
eat() # 可以不传, 是空字典
>>>{'name': 'bajie', 'age': '100'}
动态位置 + 动态关键字 : 聚合
def eat(*food1, **food2): #万能传参, * ** 相当于一个聚合的作用
print(food1, food2)
打散
def func(*food, **kwfood): #这里的 * 是聚合, 位置参数 # ** 同理
print(food, kwfood)
lst = ['bajie','wukong','datang']
dic = {'1':'1','2':'2','3':'3','4':'4'}
func(lst) #这样是传了一个参数, 是元组, 里面套了一个列表
func(*lst, **dic) #这里的 * 是打散(list,tuple, set, str), 进行迭代打散 # ** 同理, 是打散(dict)
总结:
参数
1.实参
位置参数
关键字参数
混合参数(位置+关键字)
2.形参
位置参数
默认值参数
动态传参
*args: 位置参数的动态传参
**kwargs: 关键字参数的动态传参
顺序: 位置参数, *args, 默认值参数, **kwargs