python-function Chapter

Source: Internet
Author: User

Python function basics

A. function

1. Introduction to Functions

Functions are well-organized, reusable pieces of code that are used to implement a single, or associated function.

Functions can improve the modularity of the application, and the reuse of the code. You already know that Python provides a number of built-in functions, such as print (). But you can also create your own functions, which are called user-defined functions.

1) Why use a function:

And then there's a requirement that lets you calculate the length of ' Hello World ', how do you calculate?

1 " Hello World " 2 0 3  for inch S1: 4     Length = length+156 print (length)

Well, the function is realized, very perfect. And now there is another requirement, to calculate the length of another string, "Hello HX".

1S1 ="Hello World"2Length =03  forIinchS1:4Length = length+15 6 print (length)7 8S2 ="Hello Eva"9Length =0Ten  forIinchS2: OneLength = length+1 A  -Print (length)
Result: The first program output is 11 and the second program output is 9.

This can really achieve the effect of the Len method, but the overall feeling is not so perfect? Why is it?

First, we can get the length of a string directly before we execute the Len method, and now we write the same code many times to achieve the same function-code redundancy

Second, it's easy to read just two sentences before, and we'll know that these two lines of code are calculating lengths, but just the code is not so easy to read-the readability is poor

Print (len (S1)) print (Len (S2))
Definition and invocation of primary knowledge function

There are three different parameters to the function:

General parameters

Default parameters

Dynamic parameters

Defining several elements of a function:

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

DEF is fixed, cannot be changed, must be a continuous def three letters, can not be separated ... They are going to love each other together.

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

Brackets: Must be added, do not ask why the 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

#函数定义def Mylen (S1): "" "    calculates the length of the S1" "" "Length    = 0 for I in    s1:        length = length+1    return length# function call Str_ Len = Mylen ("Hello World") print (' Str_len:%s '%str_len)
return value of the function
#函数定义def Mylen (): "" "    calculates the length of the S1" ""    S1 = "Hello World"    length = 0 for    i in S1:        length = length+1    prin T (length) #函数调用str_len = Mylen ()      because there is no return value, Str_len receives none, so the print is also Noneprint (' Str_len:%s '%str_len)

If you execute this code, the resulting Str_len value is none, which means that we have nothing to return to you in this piece of code.

So how do you get it to return a value like the Len function?

#函数定义def Mylen (): "" "    calculates the length of the S1" ""    S1 = "Hello World"    length = 0 for    i in S1:        length = length+1    Return length# function Call Str_len = Mylen () print (' Str_len:%s '%str_len)
Result: Return 11

  

order of execution of functions

We just need to add a return,return to the end of the function and write the value you want to return.

Next, let's look at the use of this return.

The function of the return keyword

Return is a keyword, and in pycharm you will see it turn blue. You have to memorize the word without any bad words.

This word translates to "return", so the value that we write after return is called "return value".

To study the return value, we also know that there are several cases of return value: No return value, return 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.

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 Mylen (): "" "    calculates the length of the S1" ""    S1 = "Hello World"    length = 0 for    i in S1:        length = length+1    Retu RN length# function Call Str_len = Mylen () print (' Str_len:%s '%str_len)

Return multiple values

Can return any number of values of any data type

Def ret_demo1 ():                #返回值如下    return 1                    #1def Ret_demo2 ():    return                  # (+) def RET_DEMO3 ():    return [' A ', ' B ']            #[' A ', ' B ']def Ret_demo4 ():    return 1,[],                # (1,[]) def ret_demo5 ():    return 1, (+), {' A ': ' B '}    # (1, (1, 2), {' A ': ' B '}), all of which receive Def RET_DEMO6 () for a value:       
Return 1, # (1,) is also a tuple returned
c= ret_demo* () print (c)---------------------------------------------------------------------------def Ret_demo5 () : return 1, {' A ': ' B '} a,b,c= Ret_demo5 () #返回多个值, receive 1 (1, 2) with multiple values {' A ': ' B '}print (A,B,C)

Summary: When a value is returned is a string, when more than one value is returned in the form of a tuple, if return ' a ', return is a.

parameters of a function

We tell the Mylen function to calculate who the string is, this process is called the Pass parameter, referred to as the argument, we call the function when the "Hello World" and the definition of the function S1 is the parameter .

Real participation Formal parameters

The parameters are also different:

The "Hello World" passed when we called the function is called the actual argument, because this is the actual content to be given to the function, referred to as the argument .

The S1 that defines a function is simply the name of a variable, called the formal parameter , because it is only a form when defining a function, which means that there is a parameter, referred to as a formal parameter.

Passing Multiple parameters

Parameters can be passed multiple, and multiple parameters are separated by commas.

def mymax (x, y):    The_max = x if x > y else y    return the_maxma = Mymax (10,20) print (MA)

  

Position parameters

Standing at the argument angle

1. Transfer Values by location

def mymax (x, y):    #此时x =10,y=20    the_max = x if x > y else y    return the_maxma = Mymax (10,20) print (MA)

2. Keyword parameters

def mymax (x, y):    #此时x = 20,y = Ten    print (x, y)    The_max = x if x > y else y    return the_maxma = Mymax (y = 10,x =) print (MA)

3. Location, keywords two forms of mixing

def mymax (x, y):    #此时x = 10,y =    print (x, y)    The_max = x if x > y else y    return the_maxma = Mymax (10,y = ) Print (MA)

  

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 of the angle

Positional parameters must be passed value

def mymax (x, y):    #此时x = 10,y =    print (x, y)    The_max = x if x > y else y    return the_max# call Mymax do not pass parameter MA = Mymax () print (MA) #结果TypeError: Mymax () missing 2 required positional arguments: ' x ' and ' Y '

  

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 stu_info (name,sex = "male"): "" "    print student information function, since most of the students in the class are boys,        the default value for setting the default parameter sex is ' Male '" ""    print (name , sex) stu_info (' Alex ') stu_info (' Eva ', ' female ')

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

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

def mysum (*args):    the_sum = 0 for    i in args:        the_sum+=i    return the_sumthe_sum = MySum (1,2,3,4) print ( The_sum)-------------------------------------------------------------------------------------------def stu_info (**kwargs):    print (Kwargs)    print (kwargs[' name '],kwargs[' sex ') stu_info (name = ' Alex ', sex = ' male ')

Function Usage Section

Rules for defining functions:

1. Definition: The DEF keyword begins with a space followed by the function name and parentheses (). 2. Parameters: Parentheses are used to receive parameters.    If multiple parameters are passed in, the parameters are separated by commas.    Parameters can be defined in multiple or undefined. There are many parameters, and if you are involved in the definition of multiple parameters, you should always follow the definition of positional parameters, *args, default parameters, **kwargs order. if a parameter type defaults during the above definition, the other parameters follow the above sort 3. Note: The first line of the function statement should add a comment. 4. Function Body: function content begins with a colon and is indented. 5. Return value: return [expression] End function. Return without an expression is equivalent to returning the NONEDEF function name (parameter 1, parameter 2,*args, default argument, **kwargs): "" "        Comment: function function and parameter description" ""        function body        ... return value

Rules for calling functions

1. The function name ()    after the function name + parentheses is the function's call. 2. Parameters:    parentheses are used to receive parameters.    if more than one parameter is passed in: the        value should be passed in the first position, and then        the specific incoming order should be determined according to the parameters defined by the function.
      
3. Return value If the function has a return value, you should also define a "variable" to receive the return value if there are multiple return values, you can also use multiple variables to receive, the number of variables should be consistent with the number of return values no return value of the case: the function name () has a return value: variable = function name () Multiple variables receive multiple return values: Variable 1, variable 2, ... = function name ()

  

  

python-function Chapter

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.