Preliminary knowledge of Python functions

Source: Internet
Author: User

First, what is a function?

Functional, well-organized, reusable code snippets used to implement a single, or associated function.

Functions can improve the modularity of the application, and the reuse of code, which is called the user-defined function

Second, the definition and invocation of functions

 #   function definition   def   Mylen ():    Calculate the length of the S1    S1  =  " hello World  "   length  = 0  for  i in   s1:length  = length+1 print   (length)  #   function call  Mylen () 
Definition: Thedef keyword begins with a space followed by the function name and parentheses (), and finally a ":".    def  is fixed and cannot be changed, he is the keyword that defines the function.   Space in order to separate the DEF keyword and function name, you must be empty (four tones), of course, you can empty 2, 3, or how much you want to empty, but normal people still empty 1. 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 parentheses: it must be added, do not ask why there is parentheses, in short, with parentheses on the right! 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. 

Third, return value of function

#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 function of the return keyword

Return is a keyword, the value after return is called "return value", many times, we need to determine the return value, whether there is, return a value, return multiple values.

No return value

If you do not write return, the default is to return a none: The first function we write does not write return, which is a case where there is no return value.

#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) Copy Code
no return value

Only write return, the back does not write other content, will also return none, some students will be strange, since there is no value to return, can not write return, why also write a return it? Here we have to say the other use of return is to end the entire function once the return is encountered .

def Ret_demo ():     Print (111)     return    Print (222= Ret_demo ()print(ret)
Write only Ruturn

Returns a value

We've just written a case that returns a value, just write what you want to return after return.

#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)
return a value

Return multiple values

Can return any number of values of any data type

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) returns multiple values
return multiple values

Iv. parameters of the function

Real participation Formal parameters

The actual value in the calling function, called the argument

When defining a function, a variable is added to the parentheses, indicating that there will be arguments coming in, called formal parameters

-----------like to explain his simple violence ...

Passing Multiple parameters

Arguments can be passed multiple, and multiple parameters are separated by commas

def Mymax (x, y    ): if Else y     return  = Mymax (10,20)print(MA) passes multiple parameters

Position parameters

Standing at the argument angle

1. Transfer Values by location

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

2. Pass the value by keyword

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

3. The position, the keyword form mixes with

def Mymax (x, y    ): # at this point x = 10,y =    Print (x,    y) if Else y     return  = Mymax (10,y =)print(MA) mixed-pass parameter
mixed-Pass parameters

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

  

defMymax (x, y):#at this point x = 10,y =    Print(x, y) The_max= XifX > YElseyreturnThe_max#calling Mymax does not pass parametersMa =Mymax ()Print(MA)#ResultsTypeerror:mymax () Missing 2 required positional arguments:'x'  and 'y'
View Code

Default parameters

1. Normal use

How to use

Why do I have a default parameter: Set the small change value to the default parameter

2. Definition of default parameters

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

3. Parameter traps: The default parameter is a mutable data type

def defult_param (a,l = []):    l.append (a)    print(l) defult_param ('  Alex') defult_param ('Egon')

Dynamic parameters

defTrans_para (*args,**Kwargs):Print(Args,type (args))Print(Kwargs,type (Kwargs)) Trans_para ("Jinxin", 12,[1,2,3,4],[3,4,], (1,4,7), {"a":"123","C": 456},country=" China"dynamic parameters, also known as the long-range parameter, is that you need to pass to the function of many parameters, the number of variables, then in this case, you use*args,**Kwargs Receive, args is the Ganso form that receives all parameters except the key-value pair, Kwargs receives only the parameters of the key-value pairs, and saves them in the dictionary. *args and **kwargs
Dynamic Parameters

Preliminary knowledge of Python 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.