Python's initial knowledge function:
(a) Why to use a function:
For example, if we are going to calculate the length of the string "Hello World" now, how can we calculate 1, direct print (len) can calculate the length, then now
With Len () This function, how can we calculate it, see the code below
Calculating string Lengths #利用for loops " Hello World " 0 for in s: 1print (length)
So we can also calculate the length of "Hello World", but if we want to calculate the length of multiple strings, do we have to write a lot of such a for loop? Can not have a tool can help us solve this problem, it can be used directly, then this tool is called a function, can be a good solution to our repeated code-----> Code Redundancy problem.
(ii) Definition and invocation of functions
Or the above example, how do we do that?
def mylen (): " Hello World " 0 for inch s: 1 Print (length)
This defines a function, and the code between and does not seem to be any different, in addition to adding a def and indentation, execute the above code, nothing results. The process above is equivalent to just doing the tools well, but we're going to have to take them out and get a piece of code.
#函数的定义def Mylen (): function for calculating length s = hello World " length = 0 For i in s:length + = 1 print (length) #函数的引用mylen ()
Summarize:
1, the function is preceded by the DEF keyword, followed by a space after the function name and parentheses (): The function name and the definition of the variable is similar, must be a letter, underscore or a number consisting of, cannot start with a number. In addition, the function name should have a certain meaning, can explain the function of functions simply. Parentheses () and colons: Must be added, 2, note: Each function should be the function and parameters of the corresponding description, in order to increase the readability of the function, written in the first line below the function, with three quotation marks. 3, the function call, the function name plus () can be.
(c) Return value of the function
To calculate the return value of a function we have to use a variable to accept Str_len=len ("Hello World"), so how does it work in a function?
def mylen (): " " function to calculate length :return: ' ""Hello World " 0 for inch s: 1 Print (length) =
But executing the above code, the discovery returns to none, stating that the function does not give you a return value. So how do you get the return value? Only need to add return
def mylen (): " " function to calculate length :return: ' ""Hello World " 0 for inch s: 1 return length =
The return keyword functions 1, returns the value of the function 2, and ends the function
The return value is divided into two cases: 1, no return value
2, there is a return value of worth is a worthwhile time to receive with a variable
When the return value is multiple variables, it can be received with a variable (returned in the form of a meta-ancestor), and several values are received with several variables.
(d) Parameters of the function
The parameters of the function are divided into arguments and formal parameters, which are received when the function is defined, and the formal parameter is passed in when the function is called. The formal parameter is divided into positional parameter, *args, default parameter, **kwargs four kinds of parameters, the formal parameter is divided according to the position to pass the parameter, according to the key word parameter, the dynamic transfer parameter (directly passes the primitive ancestor or the dictionary)
def Mylen (s): #s形参" "function parameters for length calculation s: #注释 of the length of the string to be computed, description of function and parameter functionreturn: The string to be computed:p Aram S::return: " "Length =0 forIinchS:length+=1 return(length) ret= Mylen ("Hello World") #hello World as an argument Ret2= Mylen ("12345") Ret3= Mylen ("Egon is somebody") Ret4= Mylen ("Hahahhahhahahha") print (ret) print (Ret2) print (ret3) print (RET4)
Position parameters
Standing at the argument angle
1. Pass the parameter by location
def mymax (x, y): #此时x =ten, y=ifelse y return= Mymax (ten) print (MA) by location
2, follow the key word
def mymax (x, y ): - Ten Print (x, y)ifelse y return - ) print (MA) by keyword
3, position, keyword parameter blending
def mymax (x, y ): Ten - Print (x, y)ifelse y return= Mymax ( print (MA) position, keyword mixing parameters
4, dynamic parameter transfer
def Fun (* *Kwargs): = {"a","b": }fun (**d)#返回为 {'a'b '#动态传参
Standing in the form parameter angle
positional parameters must be passed value
def mymax (x, y): #此时x = 10 , y = 20 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 " Span style= "COLOR: #800000" >y " Positional parameters must be passed
Default parameters: set parameter with small change to default parameter
def stu_info (name,sex = " male " "" " Print student information function, because most of the students in the class are boys, so the default value for the set default parameter sex is ' male " "" " print (name,sex) stu_info ( " Span style= "COLOR: #800000" >alex " ) stu_ Info ( " eva , " female "
Dynamic Parameters:
*args receive parameters that are redundant by location, combine them Cheng Yuanju output **kwargs receive multiple keyword arguments and make them into a dictionary output
def fun (a,*args,x =Ten,**Kwargs): Print (A,args,x,kwargs) Fun (1,2,3,4,5,6, x= -, y = -, z = -) #返回值为1 (2,3,4,5,6) -{'y': -,'Z': -}1 corresponds to a, (2,3,4,5,6) corresponds to args,20 x, {'y': -,'Z': -} corresponds to Kwargs
Summary: Functions primarily address code redundancy and poor readability in programming-oriented processes
Rules for function definitions:
1. Definition: DEF keyword begins with a space followed by a 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, if the definition of a variety of parameters, should always follow the positional parameters,*args, default parameters, * *Kwargs order definition. If a parameter type defaults during the definition above, other parameters follow the above ordering3. Note: The first line of a function statement should add a comment. 4. Function Body: The function contents begin with a colon and are indented. 5. Return value:returnThe [expression] End function. Return without an expression is equivalent to returning the NONEDEF function name (parameter 1, parameter 2,*args, default parameter, * *Kwargs):"""notes: Function functions and parameter descriptions"""function Body ...returnreturn value
View Code
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 parameter condition defined by the function 3. Return value If the function has a return value, you should also define "variable" to receive the return value == function name ()
View Code
Python Path initial function