Chapter IV Functions
1. Function acquaintance:
def: Keyword - Definition
Function name: and define how variables like
(): For transmission parameters:
- Parameter: the defined function () is the parameter
- Arguments: call () is the argument within
- Parameter passing: the argument to the process parameter in the call and
- Position pass arguments, parameters, arguments must correspond.
: - Define End
2. Definition and function calls
The definition of a function:
#定义函数
#def mt_len():
#函数体
def my1_len(x):
count = 0
for i in x:
count += 1
print(count)3
return count#return 的内容返回给了函数的调用。return下方的代码不执行
print(count)
#调用函数:
my_len()
3. The return value of the function
return: return value of the function
return 'a', 'b', 'c' # Results ( 'a', 'b', 'c')
return :
1. When a plurality of data returned, the tuple is returned
2.return content is returned to the calling function
Tag below 3.return not executed, and the function terminates (terminate non-cyclic)
4.return did not write the return value, or did not write return, the return value is None
4. The parameters of the function:
Priority: location parameter> keyword arguments> default parameters
Parameter 1: the time parameter is called the function definition
Positional parameters
The default parameters
Mixing parameters
2. arguments: function call when the argument is called
Positional parameters
Keyword arguments
Mixing parameters
#位置传参
def yue(a,b,c):
print(f"打开{a},{c},{b}")
yue(True,(123),[1,2,5])
def fun(a,b = 1):#b=1 默认参数
print(a,b)
fun(3)
fun(3,8)
def user(name,age,sex = "男"):#位置参数 > 默认参数, name,age是位置参数,sex = '男'是默认参数
print(name,sex,age)
user('ww','29')
def fun(a,b,c):
print(a,b,c)
fun(a=1,c=5,b=2)#关键字参数
fun(1,2,c=5)#混合参数
The benefit of the function;
- Reducing repetitive code (redundancy)
- High code readability
- The wrapper function
Dish dish:
#提示作用,没有约束作用
def fun(a:int,b:str):
print(a,b)
fun(1,2)
list1 = [1,2,3,4,5]
def fun(x):
return if "大于五"len(x) >5 else "不大于"
print(fun(list1))
#三元运算符:
#变量 = 条件成立的结果 条件判断 条件不成立的结果
enumerate: obtaining a value corresponding to its index enumeration method
def fun(x):
dic = {}
for k,v in enumerate(x):
dic[k] = v
return dic
list1 = [1,2,3,4,5,6,7,8,9,11]
print(list1)