Python Learning: initial knowledge function

Source: Internet
Author: User

The format of the simple write function and the meaning of the function preface

Before learning how to write code, in order to achieve the same function to write a lot of code, so there is a function, function is equivalent to a tool, function name is equivalent to the name of the tool, want to use when the name can be used.

summarize the advantages :

1. Avoid re-use of code.

2. Improve the readability of your code.

3. Easy to modify

Definition and invocation of a function

definition:The DEF keyword begins with a space followed by the function name and parentheses (), and finally a ":".

Spaces to separate the DEF keyword from the function name.

Function Name: Functions can only contain strings, underscores, and numbers, and cannot begin with a number. Although the function name can be random, but we give the function name or to be as short as possible, and can express function function

Brackets: Must be added.

Note: each function should have a corresponding description of the function and parameters, which should be written in the first line below the function. To enhance the readability of your code.

Call: is the function name () remember to add parentheses.

def function name (parameter 1, parameter 2):     " " function Comment ""    Print (' function body ')     return ' return value '
Standard function Formatreturn value of function

If the function call does not write the return value return, it returns none, and the return value is added to get what you want.

return keyword

  Return is a keyword that has two functions: 1. Ends the execution of a function. 2. Return the value you want to return

There are two types of return values:

1. The return value is None,

#function DefinitiondefMylen ():"""calculate the length of a S1"""S1="Hello World"length=0 forIinchS1:length= Length+1Print(length)#function CallStr_len =Mylen ()#because there is no return value, the Str_len is none at this timePrint('Str_len:%s'%str_len)
do not write return
def Ret_demo ():     Print (111)     return    Print (222= Ret_demo ()print(ret)
Write return only
def Ret_demo ():     Print (111)     return None     Print (222= Ret_demo ()print(ret)
return None

The return value of None is the above three cases.

2. The return value is a value

#function DefinitiondefMylen ():"""calculate the length of a S1"""S1="Hello World"length=0 forIinchS1:length= Length+1returnlength#function CallStr_len =Mylen ()Print('Str_len:%s'%str_len)
The return value is a

3. Multiple return values

defret_demo1 ():" "return multiple values" "     return1,2,3,4defRet_demo2 ():" "returns multiple values of any type" "    return1,['a','b'],3,4Ret1=Ret_demo1 ()Print(RET1) Ret2=Ret_demo2 ()Print(Ret2)
receive with a variable

Receive with a variable will become a primitive type

defRet_demo2 ():return1,['a','b'],3,4#returns multiple values, received with a variableRet2 =Ret_demo2 ()Print(Ret2)#returns multiple values, received with multiple variablesA,b,c,d =Ret_demo2 ()Print(a,b,c,d)#receive return values with multiple values: Returns several values, receives them with several variablesA,b,c,d =Ret_demo2 ()Print(a,b,c,d)
receive with multiple variablesParameters of the function

Tells the function to calculate what the number is to pass the argument.

The purpose of the argument is to use it in the function and bring the same formula with different numbers.

Arguments have arguments and formal parameters

arguments: The calling function is passed in.

Kind and definition order:

1. Pass the parameter by position, * () or *[] form can pass multiple position parameter

def Mymax (x, y    ): # at this time x=10,y=20    if Else y     return  = Mymax (10,20)print(MA)
pass the parameter by location

2. by keyword, **{} to pass multiple keyword parameters

def Mymax (x, y    ): # at this point x = 20,y = Ten    Print (x,    y) if Else y     return  = Mymax (y = 10,x =)print(MA)
pass key by keyword
def Mymax (x, y    ): # at this point x = 10,y =    Print (x,    y) if Else y     return  = Mymax (10,y =)print(MA)
keyword and location parameter blending

  

Correct usage

Problem one: The positional parameter must precede the keyword argument

Problem two: Only one parameter can be assigned once

Standing in the form parameter angle

Positional parameters must be passed value

3. Dynamic reference: *tup,**dict

Priority: Position--Keyword--*tup--**dict

Parameters : received when a function is defined

Kind and definition order:

1. Position parameters

2. Dynamic parameter (*args): Receives one or more positional parameters and makes up the meta-ancestor. If no value is ().

  

3. Default parameter: Sets the value of the smaller change to the default parameter.

① sets the default parameter, which is not passed when called.

② defined as variable data type--trap, not available

③ defined as immutable data type

def " male " ):    "" " print student information function, because most of the students in the class are boys,        so set the default parameter sex's default value is    ' Male '" "    Print(name,sex) stu_info ('Alex') stu_info (  'Eva','female')
Default Parameters

4. Dynamic parameter **kwargs: receive more than one keyword parameter, compose a dictionary. {} If it is not.

def mysum (*args):    = 0    for in  args:        the_sum+ =  I    return= MySum (1,2,3,4)print(the_sum)
*args Receive Location parameters
def Stu_info (* *Kwargs)    :print(Kwargs    )print(kwargs['  name'],kwargs['sex'Alex  'male')
**kwargs Keywords

Summarize

is the function and usage of each part within the functions, the wording, the remainder: slightly.

  

Python Learning: initial knowledge function

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.