Python function 1.1 function definition
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
- #下面这段代码
- A, B = 5,8
- c = a**b
- Print (c)
#改成用函数写
- Def calc (x, y):
- res = X**y
- return res #返回函数执行结果
- c = Calc (b) # result assignment to C variable
- Print (c)
1.2 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. Therefore, the parameter should be determined by the method of assignment, input and so on beforehand.
1.2.1 Default parameters
- def stu_register (Name,age,country,course):
- Print ("----Register student Information------")
- Print ("Name:", name)
- Print ("Age:", age)
- Print ("Nationality:", country)
- Print ("Course:", course)
- Stu_register ("Wang Shanbao", "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 country into the default parameter, I moved its position to the last side, and the default parameter must be behind the position parameter.
1.2.2 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=22,name= ' Alex ', course= "Python",)
1.2.3 Non-fixed parameters
If your function is not determined by how many parameters the user wants to pass, you can use the non-fixed parameter = = To send a tuple
- def stu_register (Name,age,*args): # *args will change multiple incoming parameters into a tuple form
- Print (Name,age,args)
- Stu_register ("Alex", 22)
- #输出
- #Alex () #后面这个 () is args, just because no value is passed, so it is empty
- Stu_register ("Jack", +, "CN", "Python")
- #输出
- # Jack (' CN ', ' Python ')
You can also have a **kwargs====== dictionary.
- def stu_register (Name,age,*args,**kwargs): # *kwargs will turn multiple incoming parameters into a dict form
- Print (Name,age,args,kwargs)
- Stu_register ("Alex", 22)
- #输出
- #Alex () {} #后面这个 {} is Kwargs, just because no value is passed, so it is empty
- Stu_register ("Jack", +, "CN", "Python", sex= "Male", province= "Shandong")
- #输出
- # Jack (' CN ', ' Python ') {' Province ': ' Shandong ', ' sex ': ' Male '}
1.2.4 Local Variables
- Name = "Alex Li"
- def change_name (name):
- Print ("Before change:", name)
- name = "Golden Horn king, a man with Tesla"
- Print ("After Change", name)
- Change_name (name)
- Print ("Look out for name change?", name)
#输出:
- Before Change:alex Li
- After the change King King, a man with Tesla
- Look outside, do you have a name change? Alex Li
1.2.5 variables that are defined in subroutines by global variables and local variables are called local variables, and variables defined at the beginning of a program are called global variables. 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. 1.3 Return value of function
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
1.4 Nested functions
- Name = "Alex"
- Def change_name ():
- Name = "Alex2"
- Def change_name2 ():
- Name = "Alex3"
- Print ("Layer 3rd print", name)
- Change_name2 () #调用内层函数
- Print ("Layer 2nd print", name)
- Change_name ()
- Print ("Outermost print", name)
1.5 Recursive functions
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 (10)
#输出:
- 10
- 5
- 2
- 1
Recursive properties:
- Must have a definite end condition
- Each time you enter a deeper level of recursion, the problem size should be reduced compared to the last recursion
- 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, whenever entering a function call, the stack will add a stack of frames, whenever the function returns, the stack will be reduced by a stack of frames. 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
1.5.12 points Search
- 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 ("Find number", Dataset[mid])
- Elif Dataset[mid] > Find_num: # Find the number on the left of mid
- Print ("\033[31;1m the number found in mid[%s] to the left \033[0m"% dataset[mid])
- Return Binary_search (Dataset[0:mid], find_num)
- else:# is looking for the right number on mid.
- Print ("\033[32;1m the number found in mid[%s] to the right \033[0m"% dataset[mid])
- Return Binary_search (Dataset[mid+1:],find_num)
- Else
- If dataset[0] = = Find_num: #find it
- Print ("Find numbers", dataset[0])
- Else
- Print ("No points, numbers to find [%s] not in list"% Find_num)
- Binary_search (data,66)
1.6 anonymous function (lambda expression)
An anonymous function is one that does not require an explicit function to be specified
#这段代码
- Def calc (n):
- Return N**n
- Print (Calc (10))
#换成匿名函数
- Calc = Lambda n:n**n
- Print (Calc (10))
You may say that it is not convenient to use this thing. Hehe, if it is so used, it does not improve the yarn, but the anonymous function is mainly used with other functions, as follows:
- res = map (lambda x:x**2,[1,5,7,4,8])
- For I in Res:
- Print (i)
Output
1
25
49
16
64
1.7 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.
1.8 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)
- res = Add (3,-6,abs)
- Print (RES)
1.9 Built-in functions
- ABS #绝对值
- All #判断列表里所有值都为真, return ture, otherwise return false
- Any #判断列表里有任一个值为真, returns ture, otherwise returns false
- ASCII #
- Bin #将一个数字转换为二进制
- BOOL #判断真假
- bytearray# Allow modification of strings
b = B ' abc '
c = ByteArray (b)
C[0] #97
C[0] = 90
C #bytearray (b ' zbc)
- Bytes #将输入的内容转换为bytes
- Callable #判断一个对象是否可调用 (calls are not references, executable meaning)
- Chr #给一个Asicc值, judging the result print Chr (68)? D
- Ord #字符转数字 Print (ord (' d ')
- classmethod#
- compile#
- complex# Enter a value that returns the plural ==complex (4,5)
- EXEC #执行exec括号里的代码
- Eval #执行括号里的运算
- delattr#
- Dict #生成字典
- Dir #查看内置方法
- Divmod #两个参数相除, return quotient and remainder Divmod (4,3)
- enumerate# Generating sequences
- Filter#true Sequence Print (filter (lambda x:x==1,[1,23,4))
- map# traversing the values in the list print (map (lambda x:x+1,[1,2,3))
- reduce# Cumulative print (reduce (lambda x,y:x+y,[1,2,3))
- float# Turn floating point
- format# string Formatting
- frozenset# Frozen Collection, Frozenset ({1,2,4,5,5}), read-only collection
- getattr#
- globals# Print (Globals ()) all the space in which the current program is stored
- Locals #打印局部的
- Hash #转为hash
- Hex #转为16进制
- ID #查看内存地址
- Input #输入
- int #转为整数
- Isinstance #判断是不是一个实例
- Issubclass #判断是不是一个子类
- ITER #
- Len #判断长度
- List #生成列表
- Max #输出最大值
- Memoryview #
- Min #输出最小值
- Next #
- Object #
- Oct #转为八进制
- Open #打开文件
- pow# Power operation print (POW (4,9))
- Print #打印
- property#
- Range #随机数
- REPR #
- Reversed #反转, reversible string
- Round #四舍五入 print (round (10.23,1))
- Set #生成集合
- SetAttr #
Slice #
A = range (20)
Pattern = Slice (3,8,2)
For I in A[pattern]: #等于a [3:8:2]
Print (i)
- Sorted #排序, sortable string
- Staticmethod #
- STR #生成字符串
- Sum #求和
- Super #
- Tuple #生成元组
- Type #判断数据类型
- VARs #同 Globals
- Zip #传n个列表, generating n sequences
>>> x = [+ +]
>>> y = [4,5,6]
>>> z = [7,8,9]
>>> print zip (x, y, z)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
Python (iv)