Python from introductory to combat series--Definition of catalog function
- Functions are well-organized, reusable pieces of code that are used to implement a single, or associated function.
Syntax of the function
def 函数名(参数列表): 函数体
The function code block begins with the DEF keyword, followed by the function identifier name and parentheses ();
Any incoming parameters and arguments must be placed in the middle of the parentheses, and the parentheses can be used to define the parameters.
The first line of the function statement can optionally use the document string-for storing the function description.
The function contents begin with a colon and are indented.
return [expression] ends the function, optionally returning a value to the caller. Return without an expression is equivalent to returning None.
To define a simple function
def showmsg(): print("定义一个简单的函数") return
Define a function with parameters
def showmsg1(msg): print(msg) return
Call to function
# 调用以上两个函数showmsg()showmsg1("这是一个带参数的函数")
Output Result:
To define a simple function
This is a function with parameters.
Parameters of the function
Formal parameter types that can be used when calling functions in Python:
1. Required Parameters
2. Keyword parameters
3. Default parameters
4. Indefinite length parameter
Required parameters must be passed into the function in the correct order, and the number of calls should be the same as when they were declared;
def showmsg2(msg):print(msg)returnshowmsg2("必传参数")showmsg2()
SHOWMSG2 ("Required parameters") output:
Required Parameters
SHOWMSG2 () Error:
TYPEERROR:SHOWMSG2 () Missing 1 required positional argument: ' msg '
Keyword arguments allow function calls when the order of arguments is inconsistent with declaration
def showusermsg(name, age):print(‘name is ‘, name, ‘---age is ‘, age)returnshowusermsg(age=18, name=‘SiebriaDante‘)
Output Result:
Name is Siebriadante---18
Default parameter: When a function is called, default parameters are used if no arguments are passed;
def showusermsg(name, age=18):print(‘name is ‘, name, ‘--- age is ‘, age)returnshowusermsg(name=‘SiebriaDante‘)
Output Result:
Name is Siebriadante---18
Variable length parameter: can handle more parameters than the original declaration, the declaration will not be named; variable length parameters use the asterisk (*) flag
def shownumber(msg, *num):print(msg)for x in num: print(x)shownumber("开始输出不定长参数:",10,20,30,40)
Output Result:
Start output variable length parameter:
10
20
30
40
Parameter passing
In Python, a type belongs to an object, and a variable is of no type:
In Python, strings, tuples, and numbers are objects that cannot be changed, while list,dict are objects that can be modified;
Passes an immutable object instance, passing only the value of the instance, without affecting the instance object itself
def changenumber(a): a = 10b = 20changenumber(b)print(b)
Output Result:
20
Passing a Mutable object instance, passing through the object itself, changing the value of the object, and changing the value of the object outside the function.
def changelist(mlist): mlist.append([1, 2, 3.4, 5]) print(‘函数内读取 mlist 的值:‘, mlist) returnmlist = [10, 20, 30]changelist(mlist)print(‘函数外读取 mlist 的值:‘, mlist)
Output Result:
Read the value of the mlist within the function: [10, 20, 30, [1, 2, 3.4, 5]]
Read the value of Mlist outside the function: [10, 20, 30, [1, 2, 3.4, 5]]
anonymous functions
Python uses lambda to create anonymous functions;
The body of a lambda is an expression, not a block of code. Only a finite amount of logic can be encapsulated in a lambda expression.
The lambda function has its own namespace and cannot access parameters outside its own argument list or in the global namespace.
Grammar
Lambda [arg1 [, Arg2,..... argn]]:expression
sum = lambda arg1, arg2: arg1 + arg2;# 调用sum函数print ("相加后的值为 : ", sum( 10, 20 ))print ("相加后的值为 : ", sum( 20, 20 ))
Output Result:
The added value is: 30
The added value is: 40
Variable scope
The scope of the variable determines which part of the program can access which particular variable name; Python has a total of 4 scopes, namely:
L (Local) 局部作用域E (Enclosing) 闭包函数外的函数中G (Global) 全局作用域B (Built-in) 内建作用域
Scope priority from high to Low: l--> e--> g--> B
b_count = 99999 # 内建作用域g_count = 0 # 全局作用域def outer(): e_count = 1 # 闭包函数外的函数中 def inner(): l_count = 2 # 局部作用域
Only modules, classes, and functions (Def, Lambda) in Python introduce new scopes, and other blocks of code (such as if/elif/else/, Try/except, For/while, and so on) do not introduce new scopes. In other words, the variables defined inside these statements can be accessed externally as well, as in the following code:
>>> if True:... msg = ‘my name is SiberiaDante‘...>>> msg‘my name is SiberiaDante‘>>>
The MSG variable is defined in the IF statement block and can be accessed externally
>>> def showmsg():... msg_def=‘my name is SiberiaDante‘...>>> msg_defTraceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name ‘msg_def‘ is not defined>>>
Msg_def is defined in a function, is a local variable, and cannot be accessed externally
Global variables and local variables
A variable that is defined inside a function has a local scope and defines a global scope outside the function;
Local variables can only be accessed within their declared functions, while global variables are accessible throughout the program. When a function is called, all variable names declared within the function are added to the scope. The following example:
total = 0; # 这是一个全局变量 def sum( arg1, arg2 ): total = arg1 + arg2; # total在这里是局部变量. print ("函数内是局部变量 : ", total) return total; #调用sum函数 sum( 10, 20 ); print ("函数外是全局变量 : ", total)
Output Result:
Inside the function is a local variable: 30
Outside the function is a global variable: 0
Global and Nonlocal keywords
The global and nonlocal keyword declarations are required when an internal scope wants to modify the variables of an external scope
Simply use the Global keyword declaration
>>> num = 1314>>> def showNum():... global num... print(num)... num = 520... print(num)...>>> showNum()1314520>>>
The nonlocal keyword is required to modify variables when the outer non-global scope is used
>>> def outer():... num=1314... def inner():... nonlocal num... print(num)... num = 520... print(num)... inner()...>>> outer()1314520>>>
Recursive functions
The function itself is called within the function, which is the recursive function;
def voidTe(num): if num == 1: return 1 return num * voidTe(num - 1)print(voidTe(10))
Output results
3628800
The advantage of recursive function is that the definition is simple, the logic is clear, but, in the computer, the function call is implemented through the data structure of the stack, whenever a function call is entered, the stack is added a stack frame, and whenever the function returns, the stack is reduced by a stack frame. Due to the size of the stack is not infinite, so the number of recursive calls too many, will lead to stack overflow;
10-python3 from beginner to actual combat-basic functions