Function
1. Function basic syntax and feature background summary
Now the boss lets you write a monitoring program, monitor the server's system status, when the use of indicators such as cpu\memory\disk more than the threshold of the e-mail alarm,
You emptied out all the knowledge and wrote the following code
while True: if %: #发送邮件提醒 connect a mailbox server to send a message close Connect if%: # Send a mail reminder to connect a mailbox server to send a message close if: #发送邮件提醒 Connect to a mailbox server Send mail close connection
The above code realizes the function, but even the neighbor old Wang also saw the clue, Lao Wang kindly touched the face of your son, said, you this duplicate code too much, every time the alarm to rewrite a piece of code, too low, so there are 2 problems:
- Too much code duplication, kept copy and paste not in line with high-end programmer temperament
- If you need to modify this code in the future, such as to join the mass function, then you need to use all the code in the place to modify it again
You think Lao Wang is right, you do not want to write duplicate code, but do not know how to do, Lao Wang seems to see your mind, at this time he picked up your son, smiled and said, in fact, it is very simple, just want to repeat the code extracted, put in a public place, a name, who want to use this code, the name of the call on the line As follows
def send mail (content) #发送邮件提醒 Connect mailbox server send mail close connection whileTrue:ifCPU Utilization > -%: Send mail ('CPU Alarms') ifHard disk Use space > -%: Send mail ('HDD Alarm') ifMemory Footprint > the%: Send mail ('Memory Alarms')
What is a function?
function is derived from mathematics, but the concept of "function" in programming is very different from the function in mathematics, the specific difference, we will say later, the function of programming in English also has a lot of different names. In basic it is called subroutine (sub-process or subroutine), in Pascal is called procedure (process) and function, in C only function, in Java is called method.
Definition: A function that encapsulates a set of statements by a name (function name), and to execute the function, simply call the name of its functions
Characteristics:
- Reduce duplicate code
- To make the program extensible
- Make programs easier to maintain
Syntax definitions
def sayhi (): #函数名 print ("Hello, I ' m nobody! " ) Sayhi () #调用函数
can take parameters
5,8= a**bprint (c) #改成用函数写def calc (x, y ):= x**y = Calc (b) # result assigned to c variable print (c)
2. Function parameters and local variables. function parameters and Local variables
Parametric the memory unit is allocated only when called, releasing the allocated memory unit immediately at the end of the call. Therefore, the formal parameter is only valid inside the function. Function call ends when you return to the keynote function, you can no longer use the shape parametric
Arguments can be constants, variables, expressions, functions, and so on, regardless of the type of argument, and when a function call is made, they must have a definite value in order to pass these values to the parameter. It is therefore necessary to use the assignment, input and other methods to get the parameters to determine the value
Default parameters
Look at the code below
def stu_register (name,age,country,course): Print ("----Registered Student information------") Print ("Name:", name) print ("Age :", age) print ("Nationality:", country) print ("Course:", course) Stu_register ("Wang Shanbao", A,"CN","Python_devops") Stu_register ("Zhang Jiaochun", +,"CN","Linux") Stu_register ("Liu Lao Gen", -,"CN","Linux")
Found country This parameter is basically "CN", just like we registered users on the site, such as the nationality of this information, you do not fill in, the default will be China, which is implemented by default parameters, the country into the default parameters is very simple
def stu_register (name,age,course,country="CN"):
Thus, this parameter is not specified at the time of invocation, and the default is CN, specified by the value you specify.
In addition, you may have noticed that after turning the country into the default parameter, I moved the position to the last side, why?
Key parameters
Under normal circumstances, to pass parameters to the function in order, do not want to order the key parameters can be used, just specify the parameter name, But remember a requirement is that the key parameters must be placed after the position parameter.
Stu_register (age=, name='Alex', course="python" ,)
Non-fixed parameters
If your function is not sure how many parameters the user wants to pass in the definition, you can use the non-fixed parameter
defStu_register (Name,age,*args):#*args will change multiple incoming parameters into a tuple form. Print(Name,age,args) stu_register ("Alex", 22)#Output#Alex () #后面这个 () is args, just because no value is passed, so it's empty.Stu_register ("Jack", 32,"CN","Python")#Output#Jack (' CN ', ' Python ')
can also have a **kwargs
defStu_register (Name,age,*args,**kwargs):#*kwargs will turn multiple incoming parameters into a dict form. Print(Name,age,args,kwargs) stu_register ("Alex", 22)#Output#Alex () {} #后面这个 {} is Kwargs, just because no value is passed, so it is emptyStu_register ("Jack", 32,"CN","Python", sex="Male", province="Shandong")#Output#Jack (' CN ', ' Python ') {' Province ': ' Shandong ', ' sex ': ' Male '}Local variables
name = alex Li " def Change_name (name): print ( " before change: " ,name) name = " Golden Horn King, a man with Tesla " print ( " after change " print ( " Look out for name change? ", name)
Output
Before Change:alex liafter change gold angle King, a man with Tesla look outside to see the name changed? Alex Li
Global vs. local variables
A variable defined in a subroutine is called a local variable, and a variable defined at the beginning of the program is called a global variable. The global variable scope is the entire program, and the local variable scope is the subroutine that defines the variable. When a global variable has the same name as a local variable: Local variables work within subroutines that define local variables, and global variables work in other places.
3. Return value
To get the result of the function execution, you can return the result using the return statement
Attention:
- The function stops executing and returns the result as soon as it encounters a return statement, so can also be understood as a return statement that represents the end of the function
- If return is not specified in the function, the return value of this function is None
Forcibly inserting knowledge points: nesting functions
Looking at the title above means that the function can also be nested functions? Of course
Name ="Alex" defchange_name (): Name="Alex2" defchange_name2 (): Name="Alex3" Print("3rd Layer Printing", name) change_name2 ()#calling the inner layer function Print("2nd Layer Printing", name) change_name ()Print("Outermost print", name)
At this point, what happens when you call Change_name2 () at the outermost layer?
Yes, it went wrong, why?
4. Recursion
Inside a function, you can call other functions. If a function calls itself internally, the function is a recursive function.
def Calc (n): Print (n) if int (N/2) = =0 :return n return calc (int (n/2)) Calc (10521) output:
Recursive properties:
1. There must be a clear end condition
2. Each time a deeper level of recursion is reached, the problem size should be reduced compared to the previous recursion
3. Recursive efficiency is not high, too many recursive hierarchy will lead to stack overflow (in the computer, function calls through the stack (stack) This data structure implementation, each time into a function call, the stack will add a stack of frames, whenever the function returns, the stack will reduce the stack frame. Because the size of the stack is not infinite, there are too many recursive calls, which can cause the stack to overflow.
Stack Literacy http://www.cnblogs.com/lln7777/archive/2012/03/14/2396164.html
Recursive function Practical application case, two-point search
data = [1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35] defBinary_search (dataset,find_num):Print(DataSet)ifLen (DataSet) >1: Mid= Int (len (DataSet)/2) ifDataset[mid] = = Find_num:#Find it Print("Find Numbers", Dataset[mid])elifDataset[mid] > Find_num:#find the number on the left of mid Print("\033[31;1m Find the number in mid[%s] left \033[0m"%Dataset[mid])returnBinary_search (Dataset[0:mid], find_num)Else:#find the number on the right of mid Print("\033[32;1m Find the number in mid[%s] to the right \033[0m"%Dataset[mid])returnBinary_search (dataset[mid+1:],find_num)Else: ifDataset[0] = = Find_num:#Find it Print("We got the numbers.", dataset[0])Else: Print("No, the number you're looking for [%s] is not in the list ."%find_num) binary_search (data,66)View Code5. Anonymous functions
An anonymous function is one that does not require an explicit function to be specified
# this piece of code def Calc (n): return n**nprint(calc# to anonymous function lambda n:n** N Print (Calc (10))
You may say that it is not convenient to use this thing. Oh, if it is so used, there is no yarn improvement, but the anonymous function is mainly used with other functions, as follows
res = map (lambda x:x**2,[1,5,7,4,8]) for in Res: Print(i)
Output
1
25
49
16
64
Introduction to Functional programming
function is a kind of encapsulation supported by Python, we can decompose complex tasks into simple tasks by splitting large pieces of code into functions through a layer of function calls, which can be called process-oriented programming. function is the basic unit of process-oriented program design.
Functions in functional programming the term does not refer to a function in a computer (actually a subroutine), but rather to a function in mathematics, the mapping of an independent variable. This means that the value of a function is determined only by the value of the function parameter, not by other states. For example, the sqrt (x) function calculates the square root of X, as long as x is not changed, and whenever the call is called, the value is constant.
Python provides partial support for functional programming. Because Python allows the use of variables, Python is not a purely functional programming language.
First, the definition
Simply put, "functional programming" is a "programming paradigm" (programming paradigm), which is how to write a program's methodology.
The main idea is to write the operation process as much as possible into a series of nested function calls. For example, there is now a mathematical expression:
(1 + 2) * 3-4
Traditional procedural programming, which may be written like this:
var a = 1 + 2;
var B = A * 3;
var c = b-4;
Functional programming requires the use of functions, which can be defined as different functions, and then written as follows:
var result = Subtract (multiply (add), 3), 4);
This code evolves the following and can be turned into this
Add. Multiply (3). Subtract (4)
This is basically the expression of natural language. Look at the following code, you should be able to understand its meaning at a glance:
Merge ([1,2],[3,4]). Sort (). Search ("2")
As a result, the code for functional programming is easier to understand.
To learn functional programming, do not play py, play Erlang,haskell, well, I will only so much ...
7. Higher-order functions
A variable can point to a function, which can receive a variable, and a function can receive another function as a parameter, a function called a higher order function.
def Add (x,y,f): return f (x) + f (y) = Add (3,-6, ABS)print(res)
8. Built-In Parameters
Built-in Parameter details Https://docs.python.org/3/library/functions.html?highlight=built#ascii
Jobs in this section
Have the following employee information sheet
Of course, this table is what you can say when you store files
1,alex li,22,13651054608,it,2013-04-01
Now need to this employee information file, to achieve additions and deletions to change the operation
- For fuzzy queries, the syntax supports at least 3 of the following:
- Select Name,age from staff_table where age > 22
- SELECT * from staff_table where dept = "IT"
- SELECT * from staff_table where enroll_date like "2013"
- Find the information, after printing, the last side to show the number of found
- Can create a new employee record, with the phone to do unique keys, staff_id need to increase
- Delete a specified employee information record, enter an employee ID, and delete
- To modify employee information, the syntax is as follows:
- UPDATE staff_table SET dept= "Market" where where dept = "IT"
Note: The above requirements, to fully use the function, please do your utmost to reduce duplication of code!
Python function (v)