Python (iv)

Source: Internet
Author: User

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:

    1. Reduce duplicate code
    2. To make the program extensible
    3. Make programs easier to maintain

Syntax definitions

    1. Def sayhi (): #函数名
    2. Print ("Hello, I ' m nobody!")
    3. Sayhi () #调用函数

can take parameters

    1. #下面这段代码
    2. A, B = 5,8
    3. c = a**b
    4. Print (c)

#改成用函数写

    1. Def calc (x, y):
    2. res = X**y
    3. return res #返回函数执行结果
    4. c = Calc (b) # result assignment to C variable
    5. 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
    1. def stu_register (Name,age,country,course):
    2. Print ("----Register student Information------")
    3. Print ("Name:", name)
    4. Print ("Age:", age)
    5. Print ("Nationality:", country)
    6. Print ("Course:", course)
    7. Stu_register ("Wang Shanbao", "CN", "Python_devops")
    8. Stu_register ("Zhang Jiaochun", +, "CN", "Linux")
    9. 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

    1. 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.

    1. 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

    1. def stu_register (Name,age,*args): # *args will change multiple incoming parameters into a tuple form
    2. Print (Name,age,args)
    3. Stu_register ("Alex", 22)
    4. #输出
    5. #Alex () #后面这个 () is args, just because no value is passed, so it is empty
    6. Stu_register ("Jack", +, "CN", "Python")
    7. #输出
    8. # Jack (' CN ', ' Python ')

You can also have a **kwargs====== dictionary.

    1. def stu_register (Name,age,*args,**kwargs): # *kwargs will turn multiple incoming parameters into a dict form
    2. Print (Name,age,args,kwargs)
    3. Stu_register ("Alex", 22)
    4. #输出
    5. #Alex () {} #后面这个 {} is Kwargs, just because no value is passed, so it is empty
    6. Stu_register ("Jack", +, "CN", "Python", sex= "Male", province= "Shandong")
    7. #输出
    8. # Jack (' CN ', ' Python ') {' Province ': ' Shandong ', ' sex ': ' Male '}
1.2.4 Local Variables
    1. Name = "Alex Li"
    2. def change_name (name):
    3. Print ("Before change:", name)
    4. name = "Golden Horn king, a man with Tesla"
    5. Print ("After Change", name)
    6. Change_name (name)
    7. Print ("Look out for name change?", name)

#输出:

    1. Before Change:alex Li
    2. After the change King King, a man with Tesla
    3. 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:

    1. 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
    2. If return is not specified in the function, the return value of this function is None
1.4 Nested functions
    1. Name = "Alex"
    2. Def change_name ():
    3. Name = "Alex2"
    4. Def change_name2 ():
    5. Name = "Alex3"
    6. Print ("Layer 3rd print", name)
    7. Change_name2 () #调用内层函数
    8. Print ("Layer 2nd print", name)
    9. Change_name ()
    10. 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.

    1. Def calc (n):
    2. Print (n)
    3. if int (N/2) ==0:
    4. return n
    5. Return calc (int (N/2))
    6. Calc (10)

#输出:

    1. 10
    2. 5
    3. 2
    4. 1

Recursive properties:

    1. Must have a definite end condition
    2. Each time you enter a deeper level of recursion, the problem size should be reduced compared to the last 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, 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
  1. data = [1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35]
  2. def binary_search (Dataset,find_num):
  3. Print (DataSet)
  4. If Len (DataSet) >1:
  5. mid = Int (len (DataSet)/2)
  6. If dataset[mid] = = Find_num: #find it
  7. Print ("Find number", Dataset[mid])
  8. Elif Dataset[mid] > Find_num: # Find the number on the left of mid
  9. Print ("\033[31;1m the number found in mid[%s] to the left \033[0m"% dataset[mid])
  10. Return Binary_search (Dataset[0:mid], find_num)
  11. else:# is looking for the right number on mid.
  12. Print ("\033[32;1m the number found in mid[%s] to the right \033[0m"% dataset[mid])
  13. Return Binary_search (Dataset[mid+1:],find_num)
  14. Else
  15. If dataset[0] = = Find_num: #find it
  16. Print ("Find numbers", dataset[0])
  17. Else
  18. Print ("No points, numbers to find [%s] not in list"% Find_num)
  19. 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

#这段代码

    1. Def calc (n):
    2. Return N**n
    3. Print (Calc (10))

#换成匿名函数

    1. Calc = Lambda n:n**n
    2. 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:

    1. res = map (lambda x:x**2,[1,5,7,4,8])
    2. For I in Res:
    3. 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.

    1. def add (x,y,f):
    2. return f (x) + f (Y)
    3. res = Add (3,-6,abs)
    4. Print (RES)
1.9 Built-in functions
  1. ABS #绝对值
  2. All #判断列表里所有值都为真, return ture, otherwise return false
  3. Any #判断列表里有任一个值为真, returns ture, otherwise returns false
  4. ASCII #
  5. Bin #将一个数字转换为二进制
  6. BOOL #判断真假
  7. bytearray# Allow modification of strings
    b = B ' abc '
    c = ByteArray (b)
    C[0] #97
    C[0] = 90
    C #bytearray (b ' zbc)
  8. Bytes #将输入的内容转换为bytes
  9. Callable #判断一个对象是否可调用 (calls are not references, executable meaning)
  10. Chr #给一个Asicc值, judging the result print Chr (68)? D
  11. Ord #字符转数字 Print (ord (' d ')
  12. classmethod#
  13. compile#
  14. complex# Enter a value that returns the plural ==complex (4,5)
  15. EXEC #执行exec括号里的代码
  16. Eval #执行括号里的运算
  17. delattr#
  18. Dict #生成字典
  19. Dir #查看内置方法
  20. Divmod #两个参数相除, return quotient and remainder Divmod (4,3)
  21. enumerate# Generating sequences
  22. Filter#true Sequence Print (filter (lambda x:x==1,[1,23,4))
  23. map# traversing the values in the list print (map (lambda x:x+1,[1,2,3))
  24. reduce# Cumulative print (reduce (lambda x,y:x+y,[1,2,3))
  25. float# Turn floating point
  26. format# string Formatting
  27. frozenset# Frozen Collection, Frozenset ({1,2,4,5,5}), read-only collection
  28. getattr#
  29. globals# Print (Globals ()) all the space in which the current program is stored
  30. Locals #打印局部的
  31. Hash #转为hash
  32. Hex #转为16进制
  33. ID #查看内存地址
  34. Input #输入
  35. int #转为整数
  36. Isinstance #判断是不是一个实例
  37. Issubclass #判断是不是一个子类
  38. ITER #
  39. Len #判断长度
  40. List #生成列表
  41. Max #输出最大值
  42. Memoryview #
  43. Min #输出最小值
  44. Next #
  45. Object #
  46. Oct #转为八进制
  47. Open #打开文件
  48. pow# Power operation print (POW (4,9))
  49. Print #打印
  50. property#
  51. Range #随机数
  52. REPR #
  53. Reversed #反转, reversible string
  54. Round #四舍五入 print (round (10.23,1))
  55. Set #生成集合
  56. SetAttr #
    Slice #
    A = range (20)
    Pattern = Slice (3,8,2)
    For I in A[pattern]: #等于a [3:8:2]
    Print (i)
  57. Sorted #排序, sortable string
  58. Staticmethod #
  59. STR #生成字符串
  60. Sum #求和
  61. Super #
  62. Tuple #生成元组
  63. Type #判断数据类型
  64. VARs #同 Globals
  65. 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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.