Python (iv)-function summary

Source: Internet
Author: User
Tags define local variable scope

Copyright Notice:

The author of this article is- chenxin

All the contents of this article come to chenxin summary, without my permission, no unauthorized forwarding and use.

QQ: 499741233

E-mail: [email protected]

Chapter 1th Python functions

Object oriented
Process oriented
1. Poor readability
2. Poor re-usability
Function-Type programming

2nd Chapter Custom Functions

See an example of a function: DB file content is chenxin|123

defLogin (Username,password):" "for user login:p Aram Username: User Input user name:p Aram Password: User input password: return:true, login success False, Login failed" "file_name= Open ("DB",'R')     forLineinchfile_name:line_list= Line.split ("|")        ifLine_list[0] = = Username andLINE_LIST[1] = =Password:returnTruereturnFalse

Explain:

1.DEF: keyword that represents a function

2. Function Name: The name of the function, and call the function according to the function name later

3. Function Body: A series of logical calculations in a function, such as: Sending mail

4. Return value: When the function is finished, you can return the data to the caller.

5. Parameters: Provide data for the function body (the Python function passes a parameter to pass a reference.) Instead of being re-assigned.)

1. General parameters (in strict order, the actual parameters are assigned to the formal parameters)

2. Default parameters (must be placed at the end of the parameter list)

3. Specify parameters (copy the actual parameters to the specified formal parameters)

4. Dynamic Parameters:

*args position parameters are all placed in tuples by default

**kwargs Default keyword parameters (dictionaries), all in the dictionary

5. Universal Parameters

3rd Chapter Local Variables

1. Variables defined in the program become local variables.
2. A local variable scope is a subroutine that defines the variable.
3. When global variables conflict with local variables, local variables work within subroutines that define local variables, and global variables work elsewhere

3.1 Examples:
#!/usr/bin/env pythonname="chenxin" defchange_name (name):Print("before change:", name) name="chenxin"  #Defining local Variables    Print("After chage:", name) change_name (name)Print("did you see the name change outside?", name) execution result: Before Change:chenxinafter chage: is chenxin outside to see name changed? Chenxin
Chapter 4th Global Variables

A variable defined at the beginning of a program is called a global variable.

1. Global variables define variables and must all be uppercase (unspoken rules). For example: Name= "Chenxin"

2. The function first reads the current environment variable, and if it does not, it reads the global variable, and the global variable is readable at all scopes.

3. Modifying global variables requires the first global name, which means that name is a global variable (re-assigned value).

4. Special: list, dictionary, tuple nested list, can be modified, not re-assigned value.

5th chapter built-in functions
#All #非0即真#Any ##bool #0和, empty dictionary empty list is False#callable #表示是否可执行, or whether you can call#dir #快速查看对象提供了哪些功能#Divmod #文章分页使用#Isinstance #用于判断 Whether the object is an instance of a class#Globals #列出全局变量#Locals #列出所有局部变量#Hash # #Enumerate#float#format#Frozenset #Max #最大#min #最小#sum #求和#int #整数#Hex #十进制转换十六进制#bin #十进制转二进制#Oct #十进制转十进制#filter #内部循环, parameter comparison#Map #将函数返回值添加到结果中#compile #将字符串, compiled into Python code#eval #执行表达式, and get results#exec #执行Python代码, receiving: Code or string#ID #查看内存地址#input #等待用户输入#isinstance #查看某个对象是不是某个类的实例#Issubclass ##Len #查看长度#List ##Memoryview #查看内存地址相关类#Next ##ITER #创建迭代器#Object #所有类的复类#Open ##Ord ##POW ##Print ##Property ##Range ##repr ##reversed #反转#Round ##Set #集合#Slice ##Sorted ##Staticmethod ##Str #字符串#Super #面向对象#tuple #元祖#type #类型#VARs #当前模块有哪些变量#Zip #压缩#__import__ #导入模块  #delattr ()#getattr ()#setattr ()

6th Chapter function return value

To get the result of the function execution, you can return the result with a return statement.

1. The function will stop executing and return the result as soon as it encounters a return statement, or it can be understood that the return statement represents the result of the function.

2. If return is not specified in the function, the return value of this function is none.

The 7th Chapter recursive function

Inside a function, you can call other functions. If a function calls itself internally, the function is a recursive function.

# !/usr/bin/env python def Calc (n):     Print (n)     if int (N/2) = =0        :return     nreturn calc (int (N/2) ) Calc (10)

7.1 Recursive Characteristics:

1. There must be 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 the benefits of the stack (in the computer, function calls through the stack (stack) This data results, every time into a function call, the stack will add a stack frame, stack will add a stack frame, whenever the function returns, the stack will be reduced a stack frame. Because the size of the stack is not infinite, the number of recursive calls is too many and can lead to stack benefits.

8th Chapter anonymous function

An anonymous function is a specified function that does not need to be displayed

#!/usr/bin/env pythondefCalc (n):returnn**NPrint(Calc (10)) #change to anonymous functionCalc=Lambdan:n**NPrint(Calc (10))#from the top it seems that there is no egg use, if it does not improve the hair, but the anonymous function is mainly used in conjunction with other functions, as follows:Res= Map (Lambdax:x**2,[1,5,7]) forIinchRes:Print(i)#Results:12549

9th Chapter High-order function

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.

# !/usr/bin/env python def Add (x,y,f):     return f (x) += Add (3,-6, ABS)print(res)

10th Chapter 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.

Functional programming, although it can be attributed to process-oriented programming, but the idea is closer to the mathematical calculation.
We first have to understand the concepts of computer (computer) and computational (Compute).
At the level of the computer, the CPU executes the subtraction instruction code, as well as various conditional judgments and jump instructions, so, assembly language is the most close to the computer languages.
And the calculation of the exponential meaning, the more abstract calculation, the farther away from the computer hardware.

Functional programming is a very high degree of abstraction of the programming paradigm, the purely functional programming language functions are not variable, so any function, as long as the input is determined, the output is OK, this pure function we call no side effects. In the case of programming languages that allow the use of variables, because of the variable state inside the function, the same input may get different output, so this function has side effects.
One of the features of functional programming is that it allows the function itself to be passed as a parameter to another function, and also allows a function to be returned!
Python provides partial support for functional programming. Because Python allows the use of variables, Python is not a purely functional programming language.

(1 + 2) * 3-4

#传统的过程式编程, it may be written like this:

    var a = 1 + 2;     = A * 3;     = b-4;

#函数式编程要求使用函数, we can define the operation process as a different function, as follows:

var result = Subtract (multiply (add), 3), 4);

#这就是函数式编程 (that's how much)

Python (iv)-function summary

Related Article

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.