Home > Article > Backend Development > Introduction to the basics of Python functional programming
Master the basic syntax specifications and calling methods of custom functions, and master the use and calling rules of various parameters of the function.
You can define a function with the functions you want. The following are simple rules:
Define function syntax:
def 函数标识名称(参数列表): “函数_文档字符串,对函数进行说明" 函数体 return [表达式]
By default, parameter values and parameter names are defined in the function declaration The order matches.
Defining a function only gives the function a name, specifies the parameters contained in the function, and the code block structure.
After the basic structure of this function is completed, you can execute it through another function call or directly from the Python prompt.
The output result after the call is:
In python, the type belongs to object, and the variable has no type:
a=[1,2,3] a="Runoob"
In the above code, [1,2,3] is List type, "Runoob" is String type, and variable a has no type Type, it is just a reference to an object (-a pointer), which can be a List type object or a String type object.
Everything in Python is an object. In a strict sense, we cannot say whether to pass by value or by reference. We should say passing immutable objects and passing mutable objects.
The following are the formal parameter types that can be used when calling functions:
Required parameters must be passed into the function in the correct order. The quantity when called must be the same as when declared.
Example:
ch06-demo01-args-necessary.py
When calling the greeting() function, you must pass in a parameter, otherwise a syntax error will occur:
Keyword parameters are closely related to function calls. Function calls use keyword parameters to determine the incoming parameter values.
Using keyword parameters allows the order of parameters when the function is called to be inconsistent with the order of declaration, because the Python interpreter can match parameter values with parameter names.
Example:
ch06-demo02-keyword.py
The following example uses the parameter name when the function printinfo() is called:
调用函数时,缺省参数的值如果没有传入,则被认为是默认值。
示例:
ch06-demo03-args-default.py
打印默认的age,如果age没有被传入:
注意:缺省值必须放在最后一个参数。
可能需要一个函数能处理比当初声明时更多的参数。这些参数叫做不定长参数。
适用于当参数个数不确定或根据调用情况其参数个数会动态变化的情况。
def函数名称(formal args, *args ): “函数_文档字符串" 函数体 retum [表达式]
加了星号(* )的变量名会存放所有未命名的变量参数。选择不多传参数也可,可变长参数的类型为元组。
**两个型号代表接受的是一个可变长度的 字典类型的参数。
因此,改参数必须以k-v值结构出现。
def函数名称(formal _args, **kw ): “函数_文档字符串” 函数体 retum [表达式
加了星号(** )的变量名会存放所有未命名的变量参数。选择不多传参数也可,可变长参数的类型为字典。
两个参数必须为函数定义中参数列表中的排名最后的参数。
*argv代表该参数位置可以放任意个数的数据,最终都会转换成元组数据类型在函数体内处理。
**kw代表该参数位置可以放k=v格式的数据,最终都会转换成字典类型数据安函数体内处理。
The above is the detailed content of Introduction to the basics of Python functional programming. For more information, please follow other related articles on the PHP Chinese website!