Fifth day of Learning Python

Source: Internet
Author: User
Tags function definition

First, function recursion

Two or two-point method

Third, anonymous function lambda

Iv. built-in functions

Five, the use of the module

Six, the package

First, function recursion

What is function recursion?

When invoking a function, a direct or indirect call to itself is a function recursive

def salary (N):
if n = = 1:
Return 100
Return salary (n-1) +300 #res =salary (n-1) +300 return res Unable to continue execution of Return,so res to final value after RES has not obtained final value return

Print (Salary (5))

The use and disadvantage of function recursion:

The low recursion efficiency in Python requires saving the current state at the next recursion, without the optimization method, and also restricting the hierarchy of function recursion the default level is 1000 layers, but the level of this restriction can be modified

Summarize the 3 prerequisites for recursive use of a function

1. There must be a clear end condition

2. Each time a deeper level of recursion is reached, the size of the problem 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, whenever entering a function call, the stack will add a stack of frames, whenever the function returns will be reduced by a stack of frames, because the size of the stack is not infinite, Too many times of so calls can cause stack overflow)

Modify function Recursive maximum depth

Import Sys

Sys.getrecursionlimit () #查看最大递归深度

Sys.setrecursionlimit (#修改最大递归深度为3000)

Two or two-point method

The environment used by dichotomy, an ordered and relatively large data type environment used

Example: Find the desired value in an ordered list

Procedure: Take a list of intermediate values, in turn, column push.

L=[1,2,3,4,5,6,7,8,9,12,14,100,222,444,555,666,11111]
def s (n,l):
Print (L)
If Len (L) > 0:
Mid=len (L)//2
If n > L[mid]:
L=l[mid+1:]
Elif N < L[mid]:
L=l[:mid]
Else
Print ("Find it")
Return
S (n,l) #执行上述语句后会将L进行切片, after slicing the results to their own function processing
S (100,l)

Third, anonymous function lambda

What is an anonymous function:

is a function without a name, defined use at any time, free memory after use, empty function

How anonymous functions are defined:

def func (x,y,z=0):

Return x+y+z

Lambda x,y,z=1:x+y+z

A lambda is a keyword that defines an anonymous function, and XYZ is a parameter followed by: Split, without writing return by default.

The comparison of Anonymous and named functions:

function with Name: Recycle, save name, repeat function function by name

Anonymous functions: disposable, defined at any time

Iv. built-in functions

Print (ABS ( -1)) #数字绝对值
Print (All ([1,23,3,4,0])) #接收的值是生成器对象, judging the added value inside, where the value contains None,0,false equivalent will print false, and vice versa prompt true
Print (Any ([1,0])) #接收的值是生成器对象, judging the added value inside, where all values equal to None,0,false print false, and vice versa prompt true (as long as a correct value will show true)
Print (sorted ([1,3,2,5,4,9,6])) #针对数据进行排序
Bin () #10进制转换2进制
Oct () #10进制转换8进制
Hex () #10进制转换16进制
Max () #求最大值
Min () #求最小值
Complex () #复数2 -4j print (x.real) real number print (X.IMAG) imaginary number
Sorted () #接收的值为可迭代对象功能是针对可迭代对象的排序功能
L= ' Adaf '
Reversed (L)
Round (1.2345,3) #保留小数点后3位四舍五入
Print (range) #求和, following the iterator principle, takes one value at a time
L= ' ADFADFADFADF '
Obj=slice (1,5,2)
Print (L[obj]) #设置切片规则
BOOL () #求bool值0 none null false false
Chr () #把数字通过accise的对应关系转换成字母65 -90 A-Z
Ord () #把字符通过accise码的对应关系转换成数字
Divmod (10,3) #等于10除3得到 (3,1) contains quotient and remainder
Enumerate ([1,2,3,4]) #接受可迭代对象结果是将可迭代对象的引所和元素组成一个元组
ID () #对比数据但是不是真实的内存地址, in the case of a memory address, the memory address must be
[].index () #查找列表, string index
Isinstance () #比较类型
ITER () #可迭代
Len () #计算长度
Open () #打开文件
Pow (10,2,3) #10的二次方对3取余
type# Viewing data types
Zip () #拉链
Eval #提取表达式执行 and return to execution results
s1= ' 1+2+3 '
S2= "[' A ', ' B ']"
Print (eval (S2)) [A, b]
Print (eval (S1)) 6

EXEC: Simply executes an expression or statement within a string and does not return a value

Five, the use of the module

What is a module:

#常见的场景: A module is a file that contains Python definitions and declarations (the file name is the suffix of the module name plus the. py), and the module can be used for import.

#但其实import加载的模块分为四个通用类别:
. py files written using Python
C or C + + extensions that have been compiled as shared libraries or DLLs
A folder that organizes a series of modules together (note: There is a __init__.py file under the folder, which is called a package)
Built-in modules that are written and linked to the Python interpreter using C

Why modules are needed:

#如果你退出python解释器然后重新进入, your previously defined functions or variables will be lost, so we usually write the program to a file so that it can be persisted and executed in Python test.py when needed, when test.py is called a scripting script.

#随着程序的发展, more and more functions, in order to facilitate management, we usually divide the program into a file, so that the structure of the program is clearer and easier to manage. At this point, we can not only use these files as scripts to execute, but also as a module to import into other modules, to achieve the function of reuse

#同样的原理, we can also download other written modules and then import into their own projects to use, this take doctrine, can greatly improve our development efficiency

Use of the module:

#模块可以包含可执行的语句和函数的定义, the purpose of these statements is to initialize the module, which executes only when the module name is first encountered when importing the import statement (the import statement can be used anywhere in the program and is imported multiple times for the same module. To prevent you from repeating the import, the Python optimization means that the module name is loaded into memory after the first import, and the subsequent import statement only adds a reference to the module object that has loaded the large memory, does not re-execute the statements within the module, as follows

#test. py
Import spam #只在第一次导入时才执行spam. py inside the code, the explicit effect here is to print only once ' from the spam.py ', of course, the other top-level code is also executed, but did not show the effect.
Import spam
Import spam
Import spam

‘‘‘
Execution Result:
From the spam.py
‘‘‘

When first import, the operation of the system:

#1. Create a new namespace for the source file (spam module), and the functions and methods defined in spam are the namespaces that are accessed when using global.

#2. Execute the code contained in the module in the newly created namespace, see initial import spam
Hint: What exactly did you do when you imported the module?
In fact function definitions is also ' statements ' that is
' Executed '; The execution of a module-level function definition
Enters the function name in the module ' s global symbol table.
In fact, a function definition is also a "executed" statement, and the execution of a module-level function definition puts the function name
into the Module global namespace table, using Globals () to view

#3. Create a name spam to reference this namespace
There is no difference between this name and the variable name, which is ' first class ', and the way of using spam. Name.
You can access the name defined in the spam.py file, spam. Name and name from test.py
Two completely different places.

Characteristics:

1. Each module is a separate namespace, defined in this module of the function, the namespace of the module as the global namespace, so that when we write our own module, we do not have to worry about our definition in our own module global variables will be imported, and the user's global variables conflict

Module name can be modified when 2.import module import spam as SM

3. The module search order is: In-memory loaded module-"Built-in module-" Sys.path contains the module

Six, the package

What is a package:

#官网解释
Packages is a-structuring Python ' s module namespace by using "dotted module names"
A package is a way to organize the Python module namespace by using the '. Module name '.

#具体的: The package is a folder containing __init__.py files, so we created the package in order to organize files/modules with folders.

#需要强调的是:
1. In Python3, even if there is no __init__.py file under the package, import package will still not error, and in Python2, the package must have the file, or import packet error

2. The purpose of creating the package is not to run, but to be imported to use, remember that the package is just a form of the module, the essence of the package is a module

Why should I have a package:

The essence of a package is a folder, then the only function of the folder is to organize the file as more and more features, we can not put all the functions in a file, so we use the module to organize functions, and as the module more and more, we need to use a folder to organize the module files, To improve the structure and maintainability of the program.

Precautions:

#1. Import statements about package related are also divided into import and from ... import ... Either way, regardless of location, you must follow a principle when importing: any point on the import, the left side must be a package, otherwise illegal. Can carry a series of points, such as Item.subitem.subsubitem, but all must follow this principle. But for import, there is no such restriction when it is used, and the left side of the point can be a package, a module, a function, a class (both of which can call their own properties in a point-and-click manner).

When importing Files #2, import, the name of the generated namespace from the file, import package, the name of the resulting namespace is also derived from the file, that is, the __init__.py under the package, the import package is the essence of the import of the file

Modules with the same name under the #3, package A, and package B do not conflict, such as A.A and B.A from two namespaces

Fifth day of Learning Python

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.