Seventh Python basics functions, recursion, built-in functions

Source: Internet
Author: User
Tags define local function definition variable scope

Read Catalogue

A mathematical-defined function and a function in Python

Second, why use a function

Background summary

Three functions and procedures

Four function parameters

Five local variables and global variables

Six forward reference ' function is variable '

Seven nested functions and scopes

Eight recursion

Nine anonymous functions

Ten-function programming

11 Built-in functions

12 Work in this section

A mathematical-defined function and a function in Python

Junior high School math function definition: Generally, in a change process, if there are two variables x and Y, and for each definite value of x, Y has a unique value corresponding to it, then we refer to x as the independent variable, y is called the dependent variable, Y is the function of X. The range of values of the argument x is called the definition field of the function.

such as Y=2*x

function definitions in Python: functions are a programmatic method of logical structuring and process.

function definition methods in Python:

def test (x):

"The function Definitions"

X+=1

return x

def: A keyword that defines a function

Test: Name of function

(): Internal definable parameters

"": Document description (not necessary, but it is strongly recommended to add descriptive information for your function)

X+=1: Generic code block or program processing logic

Return: Define the return value

Call run: can be with parameters or without

Function name ()

Add:

1. Functions in programming languages are distinct from those of mathematical meanings, where functions in a programming language encapsulate a string of logic used to accomplish a particular function through a function name, and the mathematical definition of a function is an equation in which the equation enters the value of the dependent variable x and it gets a result y, This is similar to a programming language (it also passes in a parameter to get a return value), different functions with mathematical meanings, the same values are passed in, the results are necessarily the same and there is no modification of any variables (no modification of the state). While the functions in the programming language pass in parameters with the same return value that are not necessarily the same and can modify other global variable values (because the execution of a function a may depend on the result of another function B, B may get different results, even if you pass the same parameter to a, the result of a will certainly be different)

2. Functional programming is: first define a mathematical function (mathematical modeling), and then follow the mathematical model in the programming language to implement it. As for the benefits of how to do this and how to do it, look at the following functional programming.

Second, why use a function

Background summary

Now the boss let you write a monitoring program, monitor the system status of the server, when the use of indicators such as cpu\memory\disk more than the threshold of the e-mail alarm, you emptied all the knowledge, wrote the following code

While True:

If CPU utilization > 90%:

#发送邮件提醒

Connecting to a Mailbox server

Send mail

Close connection

If HDD uses space > 90%:

#发送邮件提醒

Connecting to a Mailbox server

Send mail

Close connection

If memory consumption > 80%:

#发送邮件提醒

Connecting to a Mailbox server

Send mail

Close connection

def send mail (content)

#发送邮件提醒

Connecting to a Mailbox server

Send mail

Close connection

While True:

If CPU utilization > 90%:

Send mail (' CPU alert ')

If HDD uses space > 90%:

Send mail (' HDD alert ')

If memory consumption > 80%:

Send mail (' Memory alarm ')

Summarize the benefits of using a function:

1. Code Reuse

2. Maintain consistency and ease of maintenance

3. Extensibility

Three functions and procedures

Procedure definition: A procedure is simply a function with no return value

So it looks like we're talking about why the functions that we introduced when we used the function didn't return a value, and no return value was the process, yes, but there was something magical in python.

Def test01 ():

msg= ' Hello the little green frog '

Print msg

Def test02 ():

msg= ' Hello Wudalang '

Print msg

Return msg

T1=TEST01 ()

t2=test02 ()

print ' from test01 return is [%s] '%t1

print ' from test02 return is [%s] '%t2

Summary: The Python interpreter implicitly returns none when a function/procedure does not return a value using the definition returned by return.

So in Python that is, the process can also be counted as a function.

Def test01 ():

Pass

Def test02 ():

return 0

Def test03 ():

Return 0,10, ' hello ', [' Alex ', ' lb '],{' wudalang ': ' lb '}

T1=TEST01 ()

t2=test02 ()

t3=test03 ()

print ' from test01 return is [%s]: '%type (t1), T1

print ' from test02 return is [%s]: '%type (T2), T2

print ' from test03 return is [%s]: '%type (T3), T3

Summarize:

Number of return values = 0: Return None

Number of return values = 1: Return object

Number of return values >1: return tuple

Four function parameters

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

2. Arguments can be constants, variables, expressions, functions, and so on, regardless of the type of argument, and when making a function call, they must have a definite value in order to pass these values to the parameter. It is therefore necessary to use the assignment, input and other methods to get the parameters to determine the value

3. Positional parameters and keywords (standard call: Real participation parameter position one by one corresponds; keyword call: position without fixing)

4. Default parameters

5. Parameter groups

Five local variables and global variables

A variable defined in a subroutine is called a local variable, and a variable defined at the beginning of the program is called a global variable.

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 in sub-programs that define local variables, and global variables work elsewhere.

Name= ' LHF '

Def change_name ():

Print (' My name ', name)

Change_name ()

Def change_name ():

Name= ' Handsome a pen

Print (' My name ', name)

Change_name ()

Print (name)

Def change_name ():

Global Name

Name= ' Handsome a pen

Print (' My name ', name)

Change_name ()

Print (name)

Six forward reference ' function is variable '

def action ():

print ' In the action '

Logger ()

Action ()

Error Nameerror:global name ' logger ' is not defined

def logger ():

print ' In the logger '

def action ():

print ' In the action '

Logger ()

Action ()

def action ():

print ' In the action '

Logger ()

def logger ():

print ' In the logger '

Action ()

Seven nested functions and scopes

Looking at the title above means that the function can also be nested functions? Of course

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)

At this point, what happens when you call Change_name2 () at the outermost layer?

Yes, it went wrong, why?

The scope is fixed when the function is defined and does not change as the call position changes

Example one:

Name= ' Alex '

def foo ():

Name= ' LHF '

def bar ():

Print (name)

Return bar

Func=foo ()

Func ()

Example two:

Name= ' Alex '

def foo ():

Name= ' LHF '

def bar ():

Name= ' Wupeiqi '

def TT ():

Print (name)

Return TT

Return bar

Func=foo ()

Func () ()

Eight recursion

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)

Output:

10

5

2

1

Recursive ask the way

Recursive properties:

1. There must be a clear end condition

2. Each time a deeper level of recursion is reached, the problem size 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, each time into a function call, the stack will add a stack of frames, whenever the function returns, the stack will reduce the stack frame. 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

Two-point Search

Nine anonymous functions

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))

L=[3,2,100,999,213,1111,31121,333]

Print (Max (l))

dic={' K1 ': Ten, ' K2 ': +, ' K3 ': 30}

Print (max (DIC))

Print (Dic[max (Dic,key=lambda k:dic[k]))

res = map (lambda x:x**2,[1,5,7,4,8])

For I in Res:

Print (i)

Output

1

25

49

16

64

Ten-function programming

Higher order functions

Satisfies two characteristics either one is the higher order function

1. The passed-in parameter of the function is a functional name

2. The return value of a function is a functional name

Map function

Reduce function

Filter function

Summarize

Seventh Python basics functions, recursion, built-in functions

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.