Python function summary, python Summary

Source: Internet
Author: User

Python function summary, python Summary

I. Functions

1. Why use functions?

A. Avoid code reuse

B. Improve code readability

2. function call

Return Value = function name (parameter 1, parameter 2)

Function Definition-Return Value

Keyword: return

3. Function of return:

A. End function execution

B. Return the value to be returned.

4. Two situations of return values

A. the returned value is None.

Def mylen (): "Calculate the s1 length" s1 = "hello world" length = 0 for I in s1: length = length + 1 print (length) str_len = mylen () print (str_len)
Do not write return
def ret():    print(111)    return    print(222)re = ret()print(re)
Write return only
def ret():    print(111)    return None    print(222)re = ret()print(re)
Return None

B. the return value is not None.

1. Return a value

Def mylen (): "Calculate the s1 length" s1 = "hello world" length = 0 for I in s1: length = length + 1 return lengthstr_len = mylen () print (str_len)
Returns a value.

2. Multiple values are returned.

5. function call ---- accept the return value

A. the return value is None and is not accepted.

B. the return value is not None.

1. Return a value

Accept with a variable

2. Multiple values are returned.

A. Accept with a variable. The result is a ancestor.

B. Accept the number of returned values.

6. Parameters

A. Parameter ---- From the Perspective of defining functions

1. location parameters

2. Default Parameters

3. Dynamic Parameters

A. * args

B. ** kwargs

Sequence: location parameter, * args, default parameter, ** kwargs

B. Parameter ---- From the Perspective of calling a function

1. Passing parameters by location

2. Passing Parameters Based on keywords

3. dynamically passing parameters * tup, ** dic

7. parameters are divided into form parameters and real parameters.

A. Real parameters: parameters passed in when a function is called

8. location parameters

A. The location parameter must be set to a value.

def aaa(a,b):    print(a,b)aaa(1,2)
Location parameters

9. Default Parameters

A. default parameters can be left blank

def bbb(x=10):    print(x) bbb()     #x = 10 bbb(20)  #x = 20
Default parameters

10. Dynamic Parameters

Def ccc (* args): #, 5 print (args) ccc (, 5) # pass the parameter t = (, 5) by position) ccc (t) (1, 2, 3, 4, 5),) ccc (* t) (1, 2, 3, 4, 5) copy the code
Dynamic Parameters
Def ddd (** kwargs): print (kwargs) ddd (k = 'A', j = 'B') # PASS Parameters by keywords
Dynamic Parameters + keyword Parameters
def eee(*args,**kwargs):    print(args,kwargs) eee(12,123)
Dynamic, first by location parameter, then by keyword Parameter

11. namespace

A. There are three namespaces:

1. Global namespace

2. Local namespace

3. built-in namespace

B. Order of the three namespaces: built-in namespace> global namespace> local namespace

C. Values

1. Local call: local namespace> global namespace> built-in namespace

x = 1def f(x):    print(x)print(10)
View Code

2. Global Call: global namespace-> built-in namespace

x = 1def f(x):    print(x)f(10)print(x)
View Code

12. Scope

A. scope is the scope of action, which can be divided into global scope and local scope according to the effective scope.

B. global scope: includesBuilt-in namespace and global namespace, Can be referenced and globally valid at any location of the entire file

C. Local scope: local namespace, which can only be in a local scopeInternalEffective

Scope: A small scope can be used, but a large scope cannot be used. A small range of ranges from large to small (graphs) are in a small scope. If a variable is used, the current small scope is available, if you do not use your own products in a small scope, you can use the upper-level products. If you do not use the upper-level products, you can use the upper-level products, and so on. If none, an error is returned.

13. Closure

A. closures are divided:

1. Closed: internal functions

2. Package: contains references to variables in the scope of external functions

B. Common closure forms

Def hei (): x = 20 def inner (): print (x) # partial return inneri = hei () I () # global
Common closure forms

14. function value decorator

A. The essence of the decorator: Closure Functions

B. The function of the decorator: add the extension function before and after the function without changing the method of calling the original function.

def timer(func):    def inner(a):        start = time.time()        func(a)        print(time.time() - start)    return inner@timerdef func1(a):    print(a)func1(1)
Decorator with Parameters

15. The principle of opening and closing the decorator:

A. Open to expansion

B. The modification is closed.

Def timer (func): def inner (* args, ** kwargs): ''' the ''' re = func (* args, ** kwargs) to be done before the function is executed) '''return inner
The fixed method of the decorator

16. decorator application scenarios

A. Calculate the execution time of func

B. logon authentication

17. iteratable

A. the degrees of string, list, set, dictionary, and ancestor can be for loops, indicating that they can be iterated.

B. iteration is to extract data from a dataset one by one, which is called iteration.

C. indicates the corresponding iteratable sign __iter __

18. Iterative protocols

A,We hope that the content in this data type can also be obtained by using "for", so we must meet the requirements of "".

B,Iteratable protocol-any internal iteratable has a _ iter _ Method

19. iterator Protocol

A,Iterator AssociationDiscussion:Internal Implementation of _ itEr ___ Next _ Method

Differences between iteratable and iterator:Multiple iteratorsA _ next _ method is provided.

Similarities between iteratable and iterator:Can be usedFor Loop

20,Judge the iterator and the method that can be iterated 

A,First: JudgmentIs internal disconnection implemented?_ Next __

'_ NeXt __'InDiR (o)

B. Type 2

From collections import Iterable # iterations from collections import Iterator # Iterator isinstance (o, Iterable) isinstance (o, Iterator)

21. Generator

A,Generator function: General function definition. However, use the yield statement instead of the return Statement to return the result. The yield statement returns a result at a time, in the middle of each result,

Suspension FunctionStatus,So that the next time you re-execute the task

B,Generator expression: similar to list derivation. However, the generator returns an object that generates results on demand, instead of building a result list at a time.

Generator Function

Def func (): print ('aaa') a = 1 yield a # returns the first value print ('bbbbbb') yield 12 # returns the second value ret = func () # Get a generator print (ret) print (next (ret) # Take the first value print (next (ret) # Take the second value print (next (ret )) # If the third value is used, an error is returned because there is no third value.
Generator Function

22. List Derivation

Normal:

for i in range(100):    print(i*i)
N * n

List push:

l =[i*i for i in range(100)]print(l)
N * n

23. recursive functions

A. Call yourself in a function

B. the maximum number of recursive layers in Python is 997.

C,The maximum number of layers is the default in python and can be modified,But it is not recommended that you modify

D. Recursive instances

def age(n):    if n == 1:        return 40    else:        ret = age(n-1)        return ret + 2age(5)
Age Calculation

E. Recursive end mark: return

Recursive three-level menu

Menu = {'beijing': {'haidian ': {'wudaokou': {'soho ':{}, 'netease' :{}, 'Google ':{}}, 'zhongguancun ': {'iqiyi' :{}, 'car home' :{}, 'youku ':{},}, 'upgrade': {'Baidu ': {},}}, 'changping ': {'shahe': {'old boys' :{}, 'beihang ':{},}, 'tiantongyuan ':{}, 'longguan ':{},}, 'chaoyang' :{}, 'dongcheng ':{},}, 'shanghai': {'minhang': {"People's Square ": {'fried chicken shop ':{}}, 'zhabei': {'train barri': {'ctrip ':{}}, 'pudong ':{},}, 'shandong ': {},} def threeLM (menu): for key in menu: print (key) k = input (">>>") if k in menu: threeLM (menu [k]) threeLM (menu)
Level 3 menu

24. Anonymous Functions

A. Anonymous functions are simple and need to be solved using functions. An anonymous function has only one row, also called lambda.

B. function name = lambda parameter: Return Value

C. Multiple parameters can be separated by commas (,). Anonymous functions can only write one row regardless of the logic complexity. The returned value is the content after the logical execution. The returned value can be of any data type like a normal function.

add2 = lambda x,y : x+yret = add2(1,2)print(ret)
View Code
l = [1,2,3,4]print(list(map(lambda x:x*x , l)))
View Code

25. built-in functions

A. isinstance determines the Data Type of the Variable

temp = "asdfsdfs"    r = isinstance(temp, list)    print(r)

B. lambda usage:

def f1():        return 123    f2 = lambda :123    r1 = f1()    r2 = f2()    print(r1,r2)
def f3(a1,a2):        return a1 + a2    f4 = lambda a1,a2: a1 + a2    r3 = f3(1,2)    r4 = f4(3,4)    print(r3,r4) 

C. abs -- Obtain the absolute value

i = abs(-123)    print(123)

D. The remainder of divmod division-for example, paging

A = 10/3 print (a) r = divmod (3.33333335) print (r) Result)

E, eval ----- force not to convert the format of the input type

Ret = eval ("1 + 3") print (ret) Result: 4

F. filter (filter)

ret = filter(lambda x: x >22, [11,22,33,44])    for i in ret:        print(i)

G. map, whether it is map or filter, the result is an iteratable object, an iterator instance.

def f1(x):        if x % 2 == 1:           return x + 100        else:           return x    ret = map(f1, [1,2,3,4,5])    ret2 = map(lambda x: x + 100if x % 2 == 1 else x ,[1,2,3,4,5])    print(ret)    for i in ret :        print(i) 

H, max () max min () min

li = [11,22,123,1]    r = max(li)    print(r)    a = min(li)    print(a) 

G and pow (x, y) ---- calculate the power of x to the power of y

i = pow(2,100)    print(i) 

K. zip --- the value corresponding to the index in the two variables

li1 = [11,22,33,44]    li2 =["a",'VV',"c","E"]    r = zip(li1,li2)    print(r)    for i in r :        print(i)

L. open --- open, close, close

Mode description r open a file as read-only. The file pointer is placed at the beginning of the file. This is the default mode. A rb file can only be read in binary format. The file pointer is placed at the beginning of the file. This is the default mode. R + open for reading and writing files. The file pointer is placed at the beginning of the file. Rb + open the file used to read and write binary data. The file pointer is placed at the beginning of the file. W open a file and write only. If the file overwrites the file. If the file does not exist, a new file is created and written. A wb file can only be written in binary format. If the file overwrites the file. If the file does not exist, a new file is created and written. W + opens the file in the write and read modes. If the file exists, overwrite the existing file. If the file does not exist, create a new file for read/write operations. Wb + enables writing and reading files in binary format. If the file exists, overwrite the existing file. If the file does not exist, create a new file for read/write operations. A. open the file to be appended. The file pointer is at the end of the file. That is, the file is in append mode. If the file does not exist, it will create a new file for writing. The AB open file is used to append the file in binary format. The file pointer is at the end of the file. That is to say, the file is in the append mode. If the file does not exist, it will create a new file for writing. A + the method for opening an object is append and read. The file pointer is at the end of the file. This file is opened in append mode. If the file does not exist, it will create a new file for read/write operations. AB + opens a file in the additional and binary format read mode. If the file has a file pointer at the end of the file. This file is opened in append mode. If the file does not exist, it will create a new file for read/write operations.

 

 

 

 

 

 

 

 

 

 

 

 

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.