Why do you use a function
Now the python session has a big event, Len Method suddenly can't directly use ...
Let you calculate the length of ' Hello World ', how do you calculate?
This requirement is not difficult for you now, let's write it together.
S1 = "Hello world" length = 0for i in s1: length = length+1print (length)
Well, the function is realized, very perfect. And now there's another requirement, to calculate the length of another string, "Hello Eva".
So, this time your code becomes this:
S1 = "Hello world" length = 0for i in s1: length = length+1print (length) s2 = "Hello eva" length = 0for i in s2: Leng th = length+1print (length)
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
Summarize:
Why use a function?
(1) Improve code readability and avoid code redundancy
(2) function can improve the modularity of the application, and the reuse of the code.
Second, the function is defined and called.
#函数定义def Mylen (): "" " calculates the length of the S1" "" S1 = "Hello World" length = 0 for i in S1: length = length+1 prin T (length) #函数调用 Mylen ()
The above is where we wrote a function and successfully called it.
Definition: The DEF 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.
return value of the function
We've just written a function that helps us to calculate the length of the string and print the result. However, this is not the same as our Len method. Where is it different? We used to call the Len method to get a value, and we had to use a variable to receive the value.
Str_len = Len (' Hello,world ')
This str_len is the length of ' Hello,world '. Can we do that with our own function? Let's try it out, too.
#函数定义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 () print (' Str_len:%s '%str_len)
Unfortunately, if you execute this code, the resulting Str_len value is none, which means that we have nothing to return to you for 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)
The function of the return keyword
Return is a keyword
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.
#函数定义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 () #因为没有返回值 at which Str_len is Noneprint (' Str_len:%s '%str_len)
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 = Ret_demo () print (ret)
Return None: As in the above two cases, we generally do not write like this.
Def ret_demo (): print (111) return None print (222) ret = Ret_demo () print (ret)
Returns a value
We've just written a case that returns a value, just write what you want to return after return.
#函数定义def Mylen (): "" " calculates the length of the S1" "" S1 = "Hello World" length = 0 for i in S1: length = length+1 r Eturn length# function Call Str_len = Mylen () print (' Str_len:%s '%str_len)
Note: The return and return values should have a space between them, and the value of any data type can be returned
Return multiple values
Can return any number of values of any data type
Def ret_demo1 (): ' returns multiple values ' ' Return 1,2,3,4def ret_demo2 (): ' returns multiple values of any type ' ' Return 1,[' A ', ' B '], 3,4ret1 = Ret_demo1 () print (ret1) Ret2 = Ret_demo2 () print (Ret2)
Multiple values returned are returned by the organization Narimoto group, or multiple values can be used to receive
Def ret_demo2 (): return 1,[' A ', ' B '],3,4# returns multiple values, receives Ret2 = Ret_demo2 () print (Ret2) #返回多个值 with a variable, receives a,b,c,d with multiple variables = ret_ Demo2 () print (A,B,C,D) #用多个值接收返回值: Returns several values, receives a,b,c,d = Ret_demo2 () print (A,B,C,D) with several variables
Reason:
>>> #python中把用逗号分割的多个值就认为是一个元组. (1, 2) >>> 1,2,3,4 (1, 2, 3, 4) >>> (1,2,3,4) (1, 2, 3, 4)
#序列解压一 >>> a,b,c,d = (1,2,3,4) >>> a1>>> b2>>> c3>>> d4# sequence decompression two >>> a , _,_,d= (1,2,3,4) >>> a1>>> d4>>> a,*_= (1,2,3,4) >>> *_,d= (1,2,3,4) >>> A1 >>> d4# also applies to strings, lists, dictionaries, collections >>> A, B = {' name ': ' Eva ', ' Age ': +} >>> a ' name ' >>> B ' age '
Parameters of the function
Now that we've made a study of the function return value, we have already completed a function that can return the length of the string. But now this function is still not perfect, before we use the Len function to be length = Len ("Hello World"), so that I can calculate who calculates whose length. But now we write this function, can only calculate the length of a "Hello World", to change a string seems to be not. What can I do about it?
#函数定义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)
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)
It is precisely because you need to pass multiple parameters, you can pass multiple parameters, you will have the following series of parameters related to the story ...
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. Pass the value by keyword
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. The position, the keyword form mixes with
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 parameter angle
Positional parameters must be passed value
positional parameters must be passed to the parameter
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 ‘)
In actual development:
The future will also use the scene ...
Problem:
Positional parameters, default parameters, the order in which dynamic parameters are defined, and the results received?
Back to top of this chapter summary
Process-oriented programming problems: Code redundancy, poor readability, poor scalability (not easy to modify)
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 "variable" to receive the return value if the return value has more than one, 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: function name () has a return value: variable = function name () Multiple variables receive multiple return value: Variable 1, variable 2, ... = function name ()
Summary of parameters:
The path of Python--Elementary knowledge function