python--Primary Knowledge function

Source: Internet
Author: User

First, the function

1. Avoid code reuse

2. Improve the readability of your code

Second, definition and invocation of functions

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

"' Function comment '

Print (' function body ')

return value

definition :

The DEF keyword begins with a space followed by a function name and parentheses, and a colon is added to the end.

DEF is fixed and cannot be changed.

function Name: Is any combination of letters, numbers, and underscores, but cannot start with a number

Function names are generally defined as being able to represent functions.

2. Invocation of functions

return value = function name (parameter)

If the Len () function is not available now, then we need to define a function to find the length of the string

     

1. Given a string, call the function, when he does not return the value of the time returned Nulldef  length ():        s= ' Hello World '        length=0 for I in        s:                length+=1        print (length) #11print (Length ()) #None2. Return must be placed in the function, and when the function has a return value, it must be received with a variable. def  length ():        s= ' Hello World '        length=0-        i in S:                length+=1        return  lengthprint (length ()) #结果, 11# calculates the length of the string

Third , the return value of the function

  Role of 1.return: ending execution of a function

2. The first return value can be any data type.

3. The function can have a return value: if there is a return value, it must be received with a variable to be effective

No return value:

return value:

1. When no return is written, the return value of the function is None

2. When writing a return, the return value of the function is None

3.return None, the return value of the function is none (almost unused)

4.return returns a value (a variable)

5.return returns multiple values (multiple variables): Multiple values are separated by commas and returned in tuples.

receive: Can be received with a variable, or can be received with multiple variables, return a few to use a few variables to receive

Def  func ():        a=111        b=[1,2,3]        c={' a ': +, ' B ': 6}       #return a# returns a value       #return a,b,c# returns multiple values, The variables are separated by commas, and return the print (func ()) function as a tuple with one or more return values

  

1returns None when no return is writtendeffunc (): a=111b=[1,2,3]ret=func ()Print(ret)2. Return none when writing only one returndeffunc (): a=111b=[1,2,3]    returnret=func ()Print(ret)3.returnnone at the time to return to nonedeffunc (): a=111b=[1,2,3]    returnNoneret=func ()Print(ret) function does not return a value
View Code
1. Return nonedef func () when not written return (  ):    a=111    b=[1,2,3]ret=func () print (RET) 2. Return Nonedef  func () when writing only one return :    a=111    b=[1,2,3]    returnret=func () print (ret) 3.return None when return Nonedef  func ():    a=111    b=[1,2,3]    return  noneret=func () print (ret) function does not return a value

  

Method One def func ():    list=[' Hello ', ' Egon ', 11,22]    return List[-1]print (func ()) method two def func ():    list=[' Hello ', ' Egon ', 11,22]    return Listm,n,k,g=func () #print (g) Defines a list that returns the last value of the list

Iv. parameters of the function

# def Fun (s): #参数接受: Formal parameters, abbreviation parameter #     ' ' # function to         calculate the length of a string---------function #         parameter s: Accept information for the string to be evaluated--------parameter #         return: To calculate the length of the string---------return the worth of information #     ' ' #     length=0# for i in     s:#         length+=1#     return length## ret= Fun (' Helloword ') #参数传入: actual parameter, short argument # print (ret)

  

1. Arguments and formal parameters
Formal parameter: Is the argument defined when the function is defined
Arguments: Parameters passed in when a function is called
2. Passing Multiple parameters
Multiple parameters can be passed, and multiple parameters are separated by commas.
There are two ways to invoke the function simultaneous parameter in the perspective of the pass-through argument:
1. Pass the parameters according to the location
2. Follow the key word parameters
Usage: 1. The position parameter must precede the keyword parameter
2. Only one parameter can be assigned once
defMy_max (A, B):#positional parameters: defining parameters sequentially    ifA>B:returnaElse:        returnb#stand on the point of referencePrint(My_max (20,30))Print(My_max (10,20))#1. Follow the location parametersPrint(My_max (b=50,a=30))#2. Follow the key wordsPrint(My_max (10,b=30))#3. Location and keyword-pass mixingPass multiple parameters to achieve the function of the size

3. Default parameters

Usage: Why Use default parameters?

Definition: The default parameter can not be passed, the default value is used when not passed, if the pass overrides the default value.

The default value is determined when the function is defined.

Default parameter flaw: Default parameter is a mutable data type

def stu_info (name,sex = "male"): "" "    print student information function, since most of the students in the class are boys,        the default value of set default parameter sex is ' Male '" ""    print ( Name,sex) Stu_info (' Alex ') stu_info (' Taibai ', ' female ') default parameters
 def  default_param (a,l=[]): L.append (a)  print   (L) Default_param (  " alex  "  Span style= "COLOR: #000000" >) Default_param (  " rgon   " ) ------------------[  '  ,  '  egon   ' ] 

4. Dynamic Parameters

Parameters that are passed by location are uniformly received by args and saved in the form of a single tuple

Accept multiple keyword arguments by keyword, receive from Kwargs, Save as a dictionary

def Fun (a,b,*args):2     sum=a+b3 for in       args:4            sum + =I5     return  sumprint(Fun (1,5,6,4))# output 1+5+6+4 and 
defFun (a,b,**Kwargs):Print(A,b,kwargs)#pass parameters by keywordFun (A = 10,b = 20,cccc= 30,dddd = 50)#output of {' CCCC ': +, ' dddd ':defF (a,b,*args,defult=6,**Kwargs):#positional parameters, *args, default parameters, **kwargs    #print (A,b,args,defult,kwargs)    returnA,b,args,defult,kwargs#When you pass parameters: You must first pass the parameters according to the location, and then follow the key words to pass the parametersPrint(F (1,2,7,8,ccc=10,der=5))Application of *kwargs

python--Primary 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.