A mathematical-defined function and a function in Python
Second, why use a function
Background summary
Three functions and procedures
Four function parameters
Five local variables and global variables
Six forward reference ' function is variable '
Seven nested functions
Eight recursion
Nine anonymous functions
Ten-function programming
11 Built-in functions
12 Work in this section
Functions of mathematical definition and functions in Python
Junior high School math function definition: Generally, in a change process, if there are two variables x and Y, and for each definite value of x, Y has a unique value corresponding to it, then we refer to x as the independent variable, y is called the dependent variable, Y is the function of X. The range of values of the argument x is called the definition field of the function.
such as Y=2*x
function definitions in Python: functions are a programmatic method of logical structuring and process.
1 Python function definition method: 2 3 def Test (x): 4 "the function definitions" 5 x+=1 6 return x 7 8 def: Define the function's keyword 9 te ST: Function name 10 (): Can be defined as parameter 11 "": Document description (not necessary, but strongly recommend adding descriptive information for your function) X+=1: Generic code block or program processing logic return: Define return value
Call run: can be with parameters or without
Function name ()
Add:
1. Functions in programming languages are distinct from those of mathematical meanings, where functions in a programming language encapsulate a string of logic used to accomplish a particular function through a function name, and the mathematical definition of a function is an equation in which the equation enters the value of the dependent variable x and it gets a result y, This is similar to a programming language (it also passes in a parameter to get a return value), different functions with mathematical meanings, the same values are passed in, the results are necessarily the same and there is no modification of any variables (no modification of the state). While the functions in the programming language pass in parameters with the same return value that are not necessarily the same and can modify other global variable values (because the execution of a function a may depend on the result of another function B, B may get different results, even if you pass the same parameter to a, the result of a will certainly be different)
2. Functional programming is: first define a mathematical function (mathematical modeling), and then follow the mathematical model in the programming language to implement it. As for the benefits of how to do this and how to do it, look at the following functional programming.
Second, why use the function
Background summary
Now the boss let you write a monitoring program, monitor the system status of the server, when the use of indicators such as cpu\memory\disk more than the threshold of the e-mail alarm, you emptied all the knowledge, wrote the following code
1 while True:2 if CPU utilization > 90%: 3 #发送邮件提醒 4 connecting Mailbox server 5 sending mail 6 closing connection 7 8 If hard disk use space > 90%: 9 #发送邮件提醒10 connect a mailbox server send mail one by one. close Connection if memory consumption > 80%:15 #发送邮件提醒16 Connect 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 a mailbox server to send mail off connection while True: If CPU utilization > 90%: send mail (' CPU alert ') if HDD uses space > 90%: send mail (' HDD alert ') if memory consumption > 80%: Send mail (' Memory alarm ')
You look at the code written by Lao Wang, imposing a magnificent, majestic atmosphere, the code reveals a restrained arrogance, thought, Lao Wang this person is really not general, suddenly to his background more interested in, ask Lao Wang, these fancy play How do you know? Lao Wang kissed your son, smoothed out the beard that does not exist, lightly said, "The old man, when young, the division from the Kinsisa of the Silver Horn King", you listen to the "Silver Corner King" of the words, not by the Jiao body a shock, thought, true NB, no wonder the code written so 6, this "Silver Horn King" That year in the lake but named sizable the name of the big, but unfortunately later over-indulgence, died in 2016, it is a pity, only left his brother alone when the two brothers fought down the Jiangshan. At this time you look at the old king left the figure, feel your son and he more and more like ...
Summarize the benefits of using a function:
1. Code Reuse
2. Maintain consistency and ease of maintenance
3. Extensibility
Iii. Functions and processes
Procedure definition: A procedure is simply a function with no return value
So it looks like we're talking about why the functions that we introduced when we used the function didn't return a value, and no return value was the process, yes, but there was something magical in python.
1 def test01 (): 2 msg= ' Hello the Little Green frog ' 3 print msg 4 5 def test02 (): 6 msg= ' Hello Wudalang ' 7 Print msg 8 return msg 9 t1=test01 () t2=test02 () print ' from test01 Return is [%s] '%t117 print ' from test02 return is [%s] '%t2
Summary: The Python interpreter implicitly returns none when a function/procedure does not return a value using the definition returned by return.
So in Python that is, the process can also be counted as a function.
1 def test01 (): 2 Pass 3 4 def test02 (): 5 return 0 6 7 def test03 (): 8 return 0,10, ' hello ', [' Alex ', ' L B '],{' Wudalang ': ' lb '} 9 t1=test01 () one t2=test02 () t3=test03 () print ' from test01 return is [%s] : '%type (t1), t116 print ' from test02 return was [%s]: '%type (T2), t217 print ' from test03 return is [%s]: '%type (T3), T3
Summarize:
Number of return values = 0: Return None
Number of return values = 1: Return object
Number of return values >1: return tuple
Four, function parameters
1. 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
2. Arguments can be constants, variables, expressions, functions, and so on, regardless of the type of argument, and when making a function call, 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
3. Positional parameters and keywords (standard call: Real participation parameter position one by one corresponds; keyword call: position without fixing)
4. Default parameters
5. Parameter groups
Five, local variables and global 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 in sub-programs that define local variables, and global variables work elsewhere.
1 name = "Alex Li" 2 3 def change_name (name): 4 print ("Before change:", name) 5 name = "Golden Horn king, a man with Tesla" 6
print ("After Change", name) 7 8 9 change_name (name) print ("Look outside name changed?", name) 12 13 14 15 16 output, BEFO Re Change:alex Li18 after the change gold Angle King, a man with Tesla 19 outside to see the name changed? Alex Li
Six, forward reference ' function is variable '
1 def Action (): 2 print ' In the action ' 3 Logger () 4 action () 5 error Nameerror:global name ' logger ' is not defined 6 7 8 def logger (): 9 print ' In the Logger ' Def action (): One print ' in the action ' logger () 1 4 action () def action (): print ' in the action ' logger ()-Def logger (): print ' in the log Ger ' action ()
Seven, nested functions
Looking at the title above means that the function can also be nested functions? Of course
1 name = "Alex" 2 3 def change_name (): 4 name = "Alex2" 5 6 def change_name2 (): 7 name = "Alex3" 8
print ("3rd print", name) 9 change_name2 () #调用内层函数11 print ("2nd layer", 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?
Eight recursion
Inside a function, you can call other functions. If a function calls itself internally, the function is a recursive function.
1 def Calc (n): 2 print (n) 3 if int (N/2) ==0:4 return n 5 return calc (int (N/2)) 6 7 Calc (Ten) 8 9 output Out: 10 1011 512 213 1
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
Tail recursion optimization: http://egon09.blog.51cto.com/9161406/1842475
Two-point search
Nine, anonymous function
An anonymous function is one that does not require an explicit function to be specified
1 #这段代码2 def calc (n): 3 return N**N4 print (Calc) 5 6 #换成匿名函数7 calc = lambda n:n**n8 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
1 res = map (lambda x:x**2,[1,5,7,4,8]) 2 for i in Res:3 print (i) 4 5 output 6 1 7 25 8 49 9 1610 64
Ten, functional programming
http://egon09.blog.51cto.com/9161406/1842475
11 Higher order functions
Satisfies two characteristics either one is the higher order function
1. The passed-in parameter of the function is a functional name
2. The return value of a function is a functional name
Xi. built-in functions
Built-in Parameter details Https://docs.python.org/3/library/functions.html?highlight=built#ascii
12. Work in this section
Have the following employee information sheet
Of course, this table is what you can say when you store files
1 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
Can be fuzzy query, syntax support at least the following 3 kinds: Can create a new employee record, with phone to do unique key, staff_id need to increase
- 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 Basics-Functions _ recursive _ built-in functions