Python Basics (6) _ Functions

Source: Internet
Author: User

Why do I have a function?

Without differentiating the code of all functions together, the question is:

Poor code readability
Code redundancy
Code can be extended to poor

How to solve?
A function is a tool, the process of preparing a tool beforehand is to define a function, and to refer to it is a function call

Conclusion: The function must be used: defined first, then called

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

Two: Classification of functions

1. Built-in function: built-in
2. Custom functions:
def function name (parameter 1, parameter 2, ...):
"' Notes '
function body

Use of functions: first defined, then called
How to define three forms of function definition function
1 Defining an parameterless function : The execution of a function does not depend on the arguments passed in by the caller to execute, and it needs to be defined as an parameterless function

Def print_tag ():
Print (' ************************* ')


def main ():
Print_tag (' * ', 20, 3)
Print_msg (' Hello World ')
Print_tag (' * ', 20, 3)

Main ()

2 defined parameters : The execution of a function needs to be defined as an argument function when it relies on the arguments passed in by the caller to execute

def print_tag (Tag,count,line_num):
For I in Range (Line_num):
Print (Tag*count)

3 Defining an empty function : The function body is pass

def func (x, Y, z):
Pass

Three: Principles of the use of functions
The use of the function must follow: the principle of first defining after use
The definition of a function is similar to the definition of a variable, and if a function is not defined in advance, it is equivalent to referencing a nonexistent variable name

#定义阶段: Only syntax detection, no code execution

def func ():
If 1>2
Print (' Hahahahahahah ')
def func (): #语法没问题, logic is problematic, referencing a nonexistent variable name
Asdfasdfasdfasdfasdf

#调用阶段

Foo ()

Return value: can return any type

No return:none.
Return Value:value
Return VAL1,VAL2,VAL3:(Val1,val2,val3)

Return effect: Only one value can be returned, terminating the execution of the function

return value:

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

Function parameter classification:

1. Position parameter (formal parameter, actual parameter)

Positional parameters: Parameters defined sequentially in order from left to right
def foo (x, y):
Print (x)
Print (y)
Parameters defined by Location , must be passed, one more no, one less.
  Foo (===>) error
argument defined by position, corresponding to parameter one by one
Foo (2,10)

2. Keyword parameter (actual parameter)

Keyword parameter: When the argument is defined, it is defined as the Key=value form
def foo (x, y):
Print (x)
Print (y)
# foo (y=10,x=1)
Foo (y=10,x=1) #关键字参数可以不用像位置实参一样与形参一一对应, named to the value

# foo (1,z=20,10) ===> error

# foo (1,y=2,z=10) ===> error

Note: The positional argument must precede the keyword argument
Note Two: The form of an argument can be either a positional argument or a keyword argument, but a parameter cannot repeat a value

3. Default parameter (formal parameter)

Default parameters: In defining the function phase, the parameter is already assigned a value, the definition stage has the value, the call stage can not pass the value

Defined:

# def func (x,y=10):
# Print (x)
# Print (y)

Call:

# func (1,20)
# func (1)

# def func (y=10,x):
# Print (x)
# Print (y)

Application of formal parameters: Values often change need to be defined as positional parameters, values are the same in most cases, need to be defined as default arguments

The default parameter needs to be noted: must be placed behind the position parameter
Default parameters need to be aware of the problem two: default parameters are usually defined as immutable types
Default parameters need to be aware of three: default parameters are assigned only once in the definition phase

4. Variable length parameter

Variable length parameter: variable length refers to the number of arguments is not fixed

Arguments for non-keyword variable lengths defined by location: * *args

Variable-length arguments defined by keywords: * * **kwargs

Arguments for non-keyword variable length: *

When defining a function, you must pre-define how many arguments (or how many arguments can be accepted) the function requires. In general, this is fine, but there is also the case when defining a function that does not know the number of arguments (think of the printf function in c), in Python, the parameter with * is used to accept a variable number of parameters. See an example

Def FUNCD (A, B, *c):
Print a
Print B
Print "Length of C is:%d"% Len (c)
Print C
Call FUNCD (1, 2, 3, 4, 5, 6) results are
1
2
Length of C is:4
(3, 4, 5, 6)

The first two parameters are accepted by a, B, the remaining 4 parameters, all are accepted by C, C is a tuple here. When we call FUNCD, we have to pass at least 2 parameters, 2 or more parameters, put in C, if there are only two parameters, then C is an empty tuple.

Variable-length arguments defined by the keyword: * *

If the last formal parameter in a function definition has a * * (double star) prefix, all other keyword parameters other than the normal parameter will be placed in a dictionary passed to the function, such as:

Def FUNCF (A, **b):
Print a
For x in B:
Print x + ":" + str (b[x])
Call FUNCF (c= ' Hello ', b=200), execute the result
100
C: Hello
b:200

As you can see, B is a Dict object instance that accepts the keyword arguments B and c.

Used together:

# def wrapper (*args,**kwargs): #可以接受任意形式, parameters of any length
# print (args)
# Print (Kwargs)
#
#
# Wrapper (1,2,3,3,3,3,3,x=1,y=2,z=3) ===> (1,2,3,3,3,3,3,) {' X ': 1, ' Y ' =2, ' z ' =3}

Named keyword parameters: The parameter defined in the *, must be passed the value, and the truth must be in the form of a keyword to pass the value

That

Formal parameters: *args,z=10

Or:

Actual parameter: z=10

# def func (X,y=1,*args,z,**kwargs):
# Print (x)
# Print (y)
# print (args)
# print (z)
# Print (Kwargs)
#
# func (1,2,3,4,5,z=10,a=1,b=2)

Results:

# def func (X,*args,z=1,**kwargs):
# Print (x)
# print (args)
# print (z)
# Print (Kwargs)
#
# func (1,2,3,4,5,a=1,b=2,c=3)

Results:

Summary: Parameter: Positional parameter, default parameter, *args, named keyword argument, **kwargs

Five, function nesting

#函数的嵌套调用
#
# def max2 (x, y):
# if x > y:
# return X
# Else:
# return Y
#
# def max4 (a,b,c,d):
# RES1=MAX2 (A, b) #23
# RES2=MAX2 (res1,c) #23
# RES3=MAX2 (res2,d) #31
# return Res3
#
#
# Print (max4 (11,23,-7,31))


#函数的嵌套定义
Def f1 ():
def f2 ():
Def f3 ():
Print (' from F3 ')
Print (' from F2 ')
F3 ()
Print (' from F1 ')
F2 ()
# Print (F1)
F1 ()

‘‘‘
From F1
From F2
From F3

‘‘‘

Vi. namespaces

Namespaces: A binding relationship between a name and a value

Namespaces are divided into three types

  built-in namespaces: The Python interpreter comes with its own name, and the Python interpreter starts to generate

  Global Namespaces: file-level-defined names are stored with the global namespace, which is generated when a Python file executes

  local namespaces: Define names inside functions, local namespaces only take effect when functions are called, and end of function calls are invalidated

load Order of the three: built-in namespaces--global namespace--local namespace

Order of the three values : Built-in namespaces, global namespaces, local namespaces

Vii. Scope

Scope:

Scope of Action:

Global Scope: The name of the built-in namespace and the global namespace belong to the global range,
#在整个文件的任意位置都能被引用, globally valid
Local scope: The name of the local namespace belongs to the local range,
#只在函数内部可以被引用, partially effective

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

1Name='Alex'2 deffoo ():3Name='LHF'4     defBar ():5Name='Wupeiqi'6         Print(name)7         deftt ():8Name='Hedeyong'9             Print(name)Ten         returnTT One     returnBar A  -Func=foo () -Func () ()#==> Bar () () ==>tt ()
‘‘‘
Hedeyong
‘‘‘

Python Basics (6) _ Function

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.