Python_ function (top)

Source: Internet
Author: User
Tags function definition wrapper

First, the basic use of functions

‘‘‘

1 What is a function

A function is a tool that has a function

2 Why should I use a function

1 The organization structure of the program is not clear, the readability is poor

2 Code Redundancy

3 Poor scalability

3 How to use functions

The use of functions must be followed by the following principles: first defined, then called

The process of preparing the tool in advance is the definition of a function

The repairman encounters the application scenario, takes the tool, calls the function.

Grammar:

def function name (parameter 1, parameter 2,...):

"""

Document comments

"""

Code1

Code2

Code3

......

return value

def: A keyword that defines a function

Function name: is equivalent to a variable name, pointing to the memory address of the functions,

Note: The memory address of the function () can be used to perform the function body code

Parameter: The parameter is the medium in which the caller of the function passes the value of the function body code, and the parameter of the function in Python does not need to be declared type

"" "Document Comment" ": Recommended to write on

Code block: Is the concrete implementation of function body function

Return value: The result of the function body code block running

The use of a function is divided into two stages:

Definition phase: Only the syntax is detected and no code is executed

Call Stage: Run function body code

def foo ():

Xxx

Print

‘‘‘

Define First

def foo ():

Print ("from foo")

Called after

Print (foo)

Foo () # no parameter is defined, which means that no parameters are passed in the call

Define First

def bar (x, y):

Print (x)

Print (y)

Called after

Bar (' A ', 2) # # No parameter is defined, meaning that the parameter must also be passed in the call

Define the parameterless function: When the code logic of the function body does not depend on any incoming values, it does not need to define the parameters

Def print_msg ():

Print (' = ' *50)

Print (' Welecome ... '. Center (50, '))

Print (' = ' *50)

Print_msg ()

Print_msg ()

Define an argument function: When the code logic of the function body relies on the value passed in by the external caller to execute, the parameter must be defined to receive the externally passed-in value

def max2 (x, y):

# x=1

# y=3

If x > Y:

Print (x)

Else

Print (y)

MAX2 (1,4)

def max2 (x, y):

If x > Y:

return x

Else

Return y

RES=MAX2 (1,4)

Print (RES)

def foo ():

Print (' from foo ')

Bar ()

Foo ()

def bar ():

Print (' from Bar ')

def foo ():

Print (' from foo ')

Bar ()

Foo ()

# definition Phase

def foo ():

Print (' from foo ')

Bar ()

def bar ():

Print (' from Bar ')

# Call Phase

Foo ()

# definition Phase

def foo ():

Print (' from foo ')

Bar ()

# Call Phase

Foo ()

def bar ():

Print (' from Bar ')

The basic form of defining function and calling function

(1) Three forms of the defined function

1.1 No parameter function

def foo ():

Print (' from foo ')

Foo ()

1.2 Parameter function

def bar (x, y):

Print (x, y)

Bar (up to)

1.3 Null function

def func ():

Pass

Ftp

def upload ():

Pass

def download ():

Pass

def login ():

Pass

def register ():

Pass

def ls ():

Pass

(2) Three forms of the calling function

2.1 Statement Form

def foo ():

Print (' from foo ')

Foo ()

2.2 Form of an expression

def foo (x, y):

res = x + y

return res

Res=foo (#表达式形式)

Res1=foo (*100)

Print (RES1)

2.3 can be passed as a parameter to another function

def max2 (x, y):

If x > Y:

return x

Else

Return y

1 2 3

RES=MAX2 (MAX2), 3

Print (RES)

Third, the return value of the function

(1) The return value of the function needs to be noted:

1 return value no type limit

2 return value has no number limit

Returns 1 values: The call function gets the result of a value

Returns multiple values: The call function gets the result of a tuple

return 0 values, or do not write return: Call function to get the result is None

(2) Return keyword: Return is the function of the end of the flag, the function can have multiple return, but once executed, the entire function is finished

Def f1 ():

Print (' first ')

Return 1

Print (' second ')

Return 2

Print (' third ')

Return 3

RES=F1 ()

Print (RES)

Print (F1)

Count=1

While True:

Print (count)

if Count = = 3:

Return

Count+=1

Foo ()

def bar ():

Pass

def foo ():

return [1,2],1,1.3,{' x ': 1},bar

Res=foo ()

Print (RES)

def func ():

Print (' from foo ')

# return

Res=func ()

Print (RES)

Iv. Use of function parameters

The parameters of a function are divided into two main categories:

1 Formal parameters: refers to the definition of the function phase in parentheses specify the variable name, that is, the parameter essence is the "variable name"

2 argument: Refers to the value passed in parentheses in the calling function, which is the "value" of the argument Essence

The relation of the shape participates in the argument: when the function is called, the argument (value) is assigned (bound) to the parameter (the variable name),

This binding is temporarily in effect when the function is called and is invalidated after the call has ended.

def foo (x, y): # x=1 y=2

# x=1

# y=2

Print (x, y)

Foo (ON)

Specific classification of formal participation arguments

(1) Position parameters

1.1-bit parameter: a formal parameter defined sequentially from left to right in the defining function stage, called a positional parameter

Note: Any parameter defined by location must be passed, one more, and one less.

def foo (x, y):

Print (x, y)

Foo (ON)

Foo (+/-)

Foo (1,)

1.2-bit arguments: Values passed in from left to right in the calling function stage, called positional arguments

Note: Any arguments that are defined by location will correspond to the parameter one by one

def foo (x, y):

Print (x, y)

Foo (2,1)

(2) Keyword parameters

Keyword arguments: In the call function phase, the parameter value is named by the form of Key=value

Attention:

1. Can completely disrupt the order, but can still be named for the specified parameter value

2. You can mix the positional real participation keyword arguments, but be aware that:

2.1 The position argument must precede the keyword argument

2.2 cannot be assigned to a parameter repeatedly

def foo (name,age):

Print (Name,age)

Foo (' Pie ', 18)

Foo (, ' Pie ')

Foo (age=18,name= ' pie ')

Foo (' Pie ', age=18)

Foo (name= ' pie ', 18)

Foo (' Pie ', age=18,name= ' zxx ')

Open (file, mode= ' R ', Buffering=none, Encoding=none, Errors=none, Newline=none, closefd=true):

Open (' A.txt ', ' W ', encoding= ' utf-8 ')

(3) Default parameters

Default parameters: Refers to a parameter that has been assigned to a parameter at the defining function stage, which is called a formal parameter with a default value, which is referred to as the default formal parameter

Attention:

1. has been assigned during the definition phase, meaning that it is not possible to assign a value at the call stage

2. Position parameters should be placed before the default parameters

3. The value of the default parameter is fixed at the function definition stage.

4. The value of the default parameter should usually be an immutable type

def foo (x,y=2):

Print (x, y)

Foo (1)

Foo (1,3)

Foo (y=3,x=1)

def foo (y=2,x):

Print (x, y)

m=10

def foo (x,y=m):

Print (x, y)

M=20

Foo (1)

def register (name,hobby,l=[]):

L.append (Hobby)

Print ('%s's hobby is%s '% (name,l))

Register (' Jqh ', ' Piao ')

Register (' zxx ', ' Drink kidney soup ')

Register (' kxx ', ' no bathing ')

Register (' Pie ', ' read ')

def register (name, hobby, L=none):

If L is None:

L=[]

L.append (Hobby)

Print ('%s's hobby is%s '% (name, L))

Register (' Jqh ', ' Piao ', [])

Register (' zxx ', ' drink kidney soup ', [])

Register (' kxx ', ' Don't bathe ', [])

Register (' Pie ', ' read ', [])

Positional parameter vs default parameter

For most cases, the values are different and should be defined as positional parameters

For most cases where the values are the same, they should be defined as default parameters

def register (name,age,sex= ' male '):

Print (Name,age,sex)

Register (' Li Tie Egg ', 18,)

Register (' Lee Eun-egg ', 28)

Register (' Copper egg ', 38)

Register (' Liu Braised Egg ', 48)

Register (' Ryuji ya ', 19, ' female ')

(4) variable-length parameters

At the angle of the argument, the variable length refers to the number of arguments passed in that are not fixed when the function is called

The arguments cannot be defined in two ways: positional arguments, key arguments, and there must be two solutions for the formal parameter * and * *, where the class should participate in the actual argument of the overflow position

1. In the formal parameter with *: Will call the function when the overflow location argument holds the form of the Narimoto group, and then assigns the value * after the variable name

def foo (x,y,*z): #z = (3,4,5,6)

Print (x, y, z)

Foo (1,2,3,4,5,6)

2. In the argument with *: Whenever in the argument with a star, before the value of the first break it into a positional argument, and then assign the value

def foo (x,y,*z): #z = (3,4,5,6)

Print (x, y, z)

Foo (1,*[2,3,4,5,6]) # foo (1,2,3,4,5,6)

def foo (x, Y, z):

Print (x, y, z)

Foo (1,* (2,3,4,5,6)) #foo (1,2,3,4,5,6)

Foo (* ()) #foo (all in all)

Foo (* ' Hello ') #foo ()

Foo (* ' abc ') #foo (' A ', ' B ', ' C ')

3. In the formal parameter with * *: Will call the function when the Overflow keyword argument is saved to the form of a dictionary, and then assign the value * * after the variable name

def foo (x,y,**z): #z ={' z ': 3, ' a ': 1, ' B ': 2}

Print (x, y, z)

Foo (1,y=2,a=1,b=2,c=3)

4. In the argument with * *: Any in the actual argument with the star, before the value of the first break it into a keyword argument, and then to assign the value

def foo (x,y,**z): #z ={' a ': +, ' B ': 200}

Print (x, y, z)

Foo (1,**{' a ': +, ' B ': $, ' Y ': 111}) #foo (1,b=200,a=100,y=111)

def foo (x, Y, z):

Print (x, y, z)

Foo (**{' y ': 111, ' X ': 222, ' Z ': 333}) #foo (z=333,x=222,y=111)

5. Specification: In formal parameters with * and *, the variable name should be args,** followed by the variable name should be Kwargs

def foo (*args,**kwargs): #args = (1,2,3,4,5) kwargs={' a ': 1, ' B ': 2, ' C ': 3}

Print (args)

Print (Kwargs)

Foo (1,2,3,4,5,a=1,b=2,c=3)

def bar (x, Y, z):

Print (x, y, z)

def wrapper (*args,**kwargs): #args = (1,2,3,4,5,6) kwargs={' a ': 1, ' B ': 2, ' C ': 3}

Bar (*args,**kwargs)

#bar (* (1,2,3,4,5,6), **{' a ': 1, ' B ': 2, ' C ': 3}) #bar (1,2,3,4,5,6,a=1,b=2,c=3)

Wrapper (1,2,3,4,5,6,a=1,b=2,c=3)

Note: When we want to pass the parameter format of a function to a function that is passed on to its interior, it should use the following form

def bar (x, Y, z):

Print (x, y, z)

def wrapper (*args,**kwargs): #args = (up to) kwargs={' Z ': 3}

Bar (*args,**kwargs)

#bar (* (), **{' Z ': 3}) #bar (1,2,z=3)

Wrapper (1,2,z=3) # Although the call is wrapper, but to follow the bar is really the parameter standard

(5) named keyword parameter : The parameter that is placed between * and * is called the named keyword parameter

Note: The named keyword parameter must be passed as a Key=value value

def foo (x,y,*args,m,n,**kwargs): #args = (3,4,5,6,7,8)

Print (x, y) #

Print (args) # (3,4,5,6,7,8)

Print (m,n) #222, 333

Print (Kwargs)

Foo (1,2,3,4,5,6,7,8,n=333,m=222,a=1,b=2)

def foo (*,x=1,y):

Print (x)

Print (y)

Foo (y=2222,x=1111)

Foo (y=2222)

def foo (X,y=1,*args,m,**kwargs):

Print (x)

Print (y)

Print (args)

Print (m)

Print (Kwargs)

Python_ function (top)

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.