Python path: Day03---python basics 3 >> functions

Source: Internet
Author: User
Tags define local ming variable scope

The content of this section

1. Basic function syntax and features

2. Parameters

3. Local variables and global variables

4. Return value

Nested functions

5. Recursion

6. Anonymous functions

7. Higher-order functions

8. Built-in functions

Basic grammar and characteristic difference of function

Process-oriented programming: According to the business logic from top to bottom implementation of functions, often with a long code to achieve the specified function, the most common operation in the development process is to paste the copy, that is, the previously implemented code block copied to the current function.

Functional Programming: A function code is encapsulated in a function, and in the future there is no need to write again, just call the function.

Object-oriented programming: classify and encapsulate functions to make development "faster, better and stronger ..."

Characteristics

1. Reduce duplication of code

2. Make the program extensible

3. Make the program easier to maintain

Define and use
def function name (parameter):           ...    function Body    ...    return value

The definition of a function has the following main points:

    • def: A keyword that represents a function
    • Function name: the names of functions, which are called later by function name
    • Function Body: A series of logical calculations in a function, such as sending a message, calculating the maximum number in [11,22,38,888,2], etc...
    • Parameters: Providing data for the function body
    • Return value: Once the function has finished executing, it can return data to the caller.
Second, the parameters

There are three different parameters to the function:

    • General parameters
    • Default parameters
    • Key parameters
    • Dynamic parameters
##  name is called function func formal parameter, abbreviation: parameter def  func (name):    Print name #  #  ' Wupeiqi ' is called the actual parameter of function func, abbreviation: argument func ('xiaoming' the parametric only allocates memory units when called, releasing the allocated memory units immediately at the end of the call. Therefore, the formal parameter is only valid inside the function. Function call ends when a function is returned, the parametric argument can be used as a constant, variable, expression, function, 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. It is therefore necessary to use the assignment, input and other methods to get the parameters to determine the value
General Parameters
def func (*args):    print  args#  execution mode one func (11,33,4,4454,5 )#  execution mode two li = [11,2,2,3,3,4,54]func (*li)
Default Parameters
defFunc (* *Kwargs):Printargs#execution Mode oneFunc (name='xiaoming', age=18)#mode of execution twoLi = {'name':'xiaoming', Age:18,'Gender':'male'}func (**li)
Dynamic Parameters
def func (*args, * *Kwargs)    :print  args    print Kwargs
Dynamic Parameter 2
def stu_register (name,age,course,country="CN"):     Pass " " country is the key parameter under normal circumstances, to the function parameters to 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.  " "
Key ParametersThird, local variables and global variables local variables
Name = "Xiao Ming" def change_name (name):    print ("Before change:", name)    name = "Xiaoming, a man with a Dream"    print ("After Change ", name) change_name (name)  print (" Look outside name changed? ", name)

Output

Before Change:xiao mingafter change Xiao Ming, a man with a dream look outside to see the name changed? Xiao Ming
A variable defined in a subroutine by a global variable and a local variable 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 within subroutines that define local variables, and global variables work in other places. Iv. return value

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
V. 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: 10521

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.

Vi. Anonymous functions

An anonymous function is one that does not require an explicit function to be specified

#这段代码def Calc (n):    return N**nprint (calc) #换成匿名函数calc = Lambda n:n**nprint (Calc (10))

Actual use of the case list

res = map (lambda x:x**2,[1,5,7,4,8]) for I in Res:    print (i)

Output

125491664
Seven, 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.

def add (x,y,f):    return F (x) + f (y)  res = Add (3,-6,abs) print (res)
Eight, built-in parameters

Built-in Parameter details Https://docs.python.org/3/library/functions.html?highlight=built#ascii

Python path: Day03---python basics 3 >> functions

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.