The content of this section
1. Basic function syntax and features
2. Parameters and Local variables
3. Recursion
4. Introduction to Functional programming
5. Higher-order functions
1. Basic function syntax and features
Three programming Paradigms:
1. Process-oriented: process--def
2. Object-Oriented: Class--and class
3. Functional programming: Functions--def
What is a function?
The term function is derived from mathematics, but the concept of "function" in programming is very different from the function in mathematics, and the function in programming has many different names in English. In c there is only function, which is called method in Java.
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
Benefits of using Functions:
- Reduce duplicate code
- To make the program extensible
- Make programs easier to maintain
Syntax definitions
12345 |
def test(x): #函数定义方法、函数名、变量 ‘‘‘The function difinition!‘‘‘ #对该函数的描述 x+=1 #函数体
return x #返回值test(1) #调用函数 |
Function:
Def func1 ():
"' Testing1 '
Print (' In the Func1 ')
return 0
Process:
Def FUNC2 ():
"' Testing2 '
Print (' In the Func2 ')
As a result, a procedure is a function that has no return value.
can take parameters
12345678910111213 |
#下面这段代码
a,b
=
5
,
8
c
=
a
*
*
b
print
(c)
#改成用函数写
def calc(x,y):
res
=
x
*
*
y
return
res
#返回函数执行结果
c
=
calc(a,b) #结果赋值给c变量
print
(c)
|
The function of return
1, the termination function of the operation, that is, the code after return will not be executed
2, return to the location where the function is called, returns a value. For example, X=test1 (), X will receive the return value of return
3, follow-up procedures sometimes need to be based on the return value of the previous function, different judgment and operation.
return value of returns
Return 1, ' Hello ', [' Alex ', ' Wupeiqi '], {' name ': ' Alex '}
Therefore, the number of return is not specified, the type is not specified. Returns the contents of the return to the tuple in return, essentially returning a value. If you have previously had a function Def test (): With return test, the return value is the memory address of the test function.
2. Function parameters and Local variables
Call Method:
1, test () execution, () means the call function test, () can have parameters or can not
Parameters
1. Formal parameters and arguments
Formal parameter: Formal parameters, not actual, is a virtual variable, when defining functions and function body use formal parameters, the purpose is to receive the arguments when the function call (the number of arguments, the type should be corresponding to the parameter one by one)
Arguments: Actual arguments, parameters passed to the function when the function is called, can be constants, variables, expressions, functions, passed to formal arguments
The difference: The formal parameter is virtual, does not occupy the memory space, the shape parametric allocates the memory unit only when is called, the argument is a variable, occupies the memory space, the data transmits one-way, the argument transmits to the formal parameter, cannot the formal parameter passes the argument.
2, the keyword call, is independent of the formal parameter sequence, the location call corresponds to the parameter one by one.
"Note": the keyword parameter cannot be written before the position parameter
3. Default parameters
def test (x,y=2):
Print (x, y)
Test (1)
The procedure for assigning parameters to a parameter when defining a function is called setting the default parameter, and the assigned value is called the default parameter of the corresponding parameter.
Default parameter feature: When a function is called, the default parameter must not be passed
4. Parameter group:
1) def test (*args):
Print (args)
Test (1,2,3,4,5) #或者等价于后面这种赋值方式: Test (*[1,2,3,4,5])
Output: (1,2,3,4,5)
All 5 positional arguments are passed to the parameter args and are saved as tuples. When you define a location call parameter group, the name of args can be arbitrary, beginning with *. But writing a specification is *args.
2) def test2 (**kwargs):
Print (Kwargs)
Test2 (Name= ' Gavin ', age=25,sex= ' M ') #或者等价于后面这种赋值方式: test2 (**{' name ': ' Gavin ', ' age ': +, ' sex ': ' m '})
Output: {' name ': ' Gavin ', ' age ': +, ' sex ': ' M '}
At this time, the arguments of the 3 key calls are passed to the parameter Kwargs, and saved as a dictionary, the keyword is key, and the value assigned to the keyword is values. When you define a keyword to invoke a parameter group, the Kwargs name can be arbitrary, starting with * *, but writing the specification is **kwargs.
3) Summary:
*args the n position parameter, the way to convert the Narimoto group
**kwargs the way to convert n keyword arguments into a dictionary
"Note": The parameter group must be placed on the last side of the formal parameter
Position parameters must be written before the keyword parameter. Therefore, the corresponding, formal parameter part of the first write *args, and then write **kwargs.
Local variables
12345678910 |
name
=
"Alex Li"
def
change_name(name):
print
(
"before change:"
,name)
name
=
"金角大王,一个有Tesla的男人"
print
(
"after change"
, name)
change_name(name)
print
(
"在外面看看name改了么?"
,name)
|
Output
123 |
before change: Alex Li after change 金角大王,一个有Tesla的男人 在外面看看name改了么? 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 scope of a global variable is the entire program, including the interior of all functions, 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.
Modifying global variables within a function
Name= ' Gavin
def change_name (name):
Global Name
Name= ' Gavin Simons '
Pass
Chang_name (name)
In this case, using the global directive inside the function declares that name is a global variable, and when the name is modified inside the function, the global variable is modified. At the same time, if a global variable is declared at the beginning of a function without a global variable with the same name, the global variable inside the function is newly created and can be called outside the function. However, although this is possible, never do this (including modifying global variables within a function and creating global variables within a function) because it is difficult to debug, and it is not known that the function created or modified the global variable.
Special cases for local variables and global variables
names=[' Gavin ', ' Simons ', ' Jack ', ' Rain ']
Def chang_name ():
Names[0] = ' James Simons '
Print (' Inside Func ', names)
Change_name ()
Print (names)
Output: Inside func [' James Simons ', ' Simons ', ' Jack ', ' Rain ']
[' James Simons ', ' Simons ', ' Jack ', ' Rain ']
So only simple data types such as strings and integers cannot be modified in the function. But complex data types (for example, lists, dictionaries, collections, classes, tuples cannot be changed at any time) are all in the local can be changed directly to the global. Because the storage method differs from the simple data type, the latter stores the address, not the specific value.
3. Recursion
Inside a function, you can call other functions. If a function calls itself internally, the function is a recursive function.
12345678910111213 |
def
calc(n):
print
(n)
if
int
(n
/
2
)
=
=
0
:
return
n
return
calc(
int
(n
/
2
))
calc(
10
)
输出:
10
5
2
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
Recursive function Practical application case, two-point search
12345678910111213141516171819202122232425 |
data
=
[
1
,
3
,
6
,
7
,
9
,
12
,
14
,
16
,
17
,
18
,
20
,
21
,
22
,
23
,
30
,
32
,
33
,
35
]
def
binary_search(dataset,find_num):
print
(dataset)
if
len
(dataset) >
1
:
mid
=
int
(
len
(dataset)
/
2
)
if
dataset[mid]
=
=
find_num:
#find it
print
(
"找到数字"
,dataset[mid])
elif
dataset[mid] > find_num :
# 找的数在mid左面
print
(
"\033[31;1m找的数在mid[%s]左面\033[0m"
%
dataset[mid])
return binary_search(dataset[
0
:mid], find_num)
else
:
# 找的数在mid右面
print
(
"\033[32;1m找的数在mid[%s]右面\033[0m"
%
dataset[mid])
return
binary_search(dataset[mid
+
1
:],find_num)
else
:
if
dataset[
0
]
=
=
find_num:
#find it
print
(
"找到数字啦"
,dataset[
0
])
else
:
print
(
"没的分了,要找的数字[%s]不在列表里"
%
find_num)
binary_search(data,
66
)
|
4. 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);
As a result, the code for functional programming is easier to understand.
To learn functional programming, do not play py, play Erlang,haskell.
5. 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.
That is, the function itself is treated as a parameter and passed to another function.
123456 |
< Code class= "python keyword" >def add (x,y,f): #f为一个函数形参 return f (x) + f (y) res = add ( 3 - 6 abs print (res) |
Python Full stack Development-day3-python Foundation 3