Before you say a function, say the following table, as mentioned above, a list can be nested in multiple lists, as follows
Software testing = [' Functional testing ',' automated testing ',' safety test ', [ ' Performance Testing ', [' script development ',' pressure measurement ',' Performance tuning ']]
But how do you print each nested list element directly with print?
We see that using the print compiler just prints it as an element, which is certainly not possible, with a for loop?
Software testing = ['Functional Testing','Automated Testing','Security Testing',['Performance Testing',['Scripting Development','Pressure Measurement','Performance Tuning']]] forEach_iteminchSoftware Testing:Print(Each_item)
The above code shows the result as
Functional test automation Test safety test [' performance test ', [' script development ' ' pressure measurement " Performance tuning "]
We see that for loop only prints individual items in the outer list, how do we handle them?
First, each time the list of one item, you have to check whether the item itself is a list, if it is a list, before processing the next item, to deal with the list before, how to judge, yes, with our familiar if ... else ...
So the question is, how to tell if a certain item is a list?
Here you can use a python built-in BIF (built-in function):isinstance () open judgment, as follows
Software testing = ['Functional Testing','Automated Testing','Security Testing',['Performance Testing',['Scripting Development','Pressure Measurement','Performance Tuning']]] forEach_iteminchSoftware Testing:ifIsinstance (each_item,list):#determine if each element is a list forNested_iteminchEach_item:Print(Nested_item)Else: Print(Each_item)
The above code shows the result as
Functional test automation test safety test Performance test [' script development ' ' measurement ' performance tuning ']
This is a bit better, but the improvement is not big, there is a nested not to be handled correctly, how to do, add another layer,
Software testing = ['Functional Testing','Automated Testing','Security Testing',['Performance Testing',['Scripting Development','Pressure Measurement','Performance Tuning']]] forEach_iteminchSoftware Testing:ifIsinstance (each_item,list):#determine if each element is a list forNested_iteminchEach_item:ifisinstance (nested_item,list): forDeeper_iteminchNested_item:Print(Deeper_item)Else: Print(Nested_item)Else: Print(Each_item)
The above code shows the result as
Functional Test automation Test safety Test Performance test Script development pressure Measurement performance tuning
This is finally good, but what if we nest a list again? It's impossible to add a for loop.
OK, we need to solve this problem with the function we're talking about today.
Software testing = ['Functional Testing','Automated Testing','Security Testing',['Performance Testing',['Scripting Development','Pressure Measurement','Performance Tuning']]]defprint_lol (the_list): forEach_iteminchthe_list:ifisinstance (each_item,list): Print_lol (Each_item)Else: Print(Each_item) print_lol (software test)#calling Functions
The above code shows the result as
Functional Test automation Test safety Test Performance test Script development pressure Measurement performance tuning
What is a function?
The term function is derived from mathematics, but the concept of "function" in programming is very different from the function in mathematics, and the function in programming has many different names in English. In basic it is called subroutine (sub-process or subroutine), in Pascal is called procedure (process) and function, in C only function, in Java is called method.
Definition: A function is a collection of a set of statements by a name (function name) encapsulated, in order to execute this function, just call its function name.
II. Benefits of using functions:
1. Simplified code
2, improve the reusability of code
3, code can be extended
Third, the definition of functions in Python:
The definition function uses the DEF keyword, followed by the function name, and the function name cannot be duplicated
def Fun ():# defines a function, followed by the name print("HelloWorld") # function Body
Of course, the above function does not have any eggs, just write a function definition example.
Iv. parameters of the function
When a function is called, it can pass in parameters, tangible parameters and arguments
Formal parameters:
Parametric the memory unit is allocated only when called, releasing the allocated memory unit immediately at the end of the call. Therefore, the formal parameter is only valid inside the function.
Actual parameters:
Arguments can be constants, variables, expressions, functions, and so on, regardless of the type of argument, and when a function call is made, they must have a definite value in order to pass these values to the parameter. The parameter variable can no longer be used after the function call finishes returning the keynote function.
def Calc (x, y):# defines a function with parameters x and Y,x and y being the parameter print(x*y)# output x multiplied by Y value Calc (5,2)# calls the functions defined above, 5 and 2 are arguments
Simply put, the parameter is the argument that the function receives, and the argument is the one you actually passed in.
The four types of parameters for a function:
Position parameters:
Positional parameters, which are literally meant to be passed as parameters, such as the Calc function above, where x and y are positional parameters, the positional parameters must be passed,
There are several positional parameters at the time of the call to pass a few, otherwise it will be error, if there are multiple positional parameters, you can not remember which location to pass what to do, you may use the name of the positional parameter to specify the call
For example, the Calc function above can also be called by using Calc (y=1,x=2), which is called the keyword argument.
Default parameters:
The default parameter is when you define formal parameters, assign a value to the function by default, such as the port of the database, the default is to give it a value, so that even if you do not pass this parameter in the call, it is also a value
So, the default parameter is not required, and if you pass the value to the default parameter, it will use the value you passed in. If a default value parameter is used, it must be defined after the position parameter.
defConn_mysql (user,passwd,port=3306):#define a way to connect to MySQL, although this method is not connected to MySQL, I just give the example of a default value parameter, port is a default value parameter Print(User,passwd,port) coon_mysql ('Root','123456')#no default value specifiedCoon_mysql ('Root','123456', port=3307)#Specify the value of the default value parameter
Non-fixed parameters:
The above two positional parameters and the default parameters are the number of parameters is fixed, if I am a function, the parameters are not fixed, I do not know the future of this function will expand into what kind of, may be more and more parameters, this time if the fixed parameters, then the program is not good expansion, then you can use non-fixed parameters, There are two types of non-fixed parameters, one is a variable parameter and one is a keyword parameter.
Variable parameters:
Variable parameters are received with *, the number of arguments to pass after the number of passes, if the positional parameters, default parameters, variable parameters used together, the variable parameter must be in the position parameter and the default value parameter. Variable parameters are also non-mandatory.
defMore_arg (name,age,sex='nan', *agrs):#positional parameters, default value parameters, variable parameters, variable parameters will be placed in the next multiple arguments to the args this tuple #of course, the args name is casually written, but generally we write the args Print(Name,age,agrs) More_arg ('Marry', 18,'NV','python',' China')#called
Keyword parameters:
Keyword parameter use * * to receive, the following parameters are not fixed, want to write how many write how many, of course, can also be used with the above several, if you want to use the keyword parameter must be in the last side.
With keyword arguments, you must use the keyword argument when calling. Keyword parameters are also non-mandatory.
def Kw_arg (Name,**kwargs):# positional parameter, keyword parameter, when called will put the passed keyword parameter in Kwargs this dictionary Print (Name,kwargs) kw_arg ('sriba', sex=' man ' , age=18)# call, sex and age are the keyword calls
V. Return value of a function
Each function has a return value, if it is not specified in the function of the return value, after the function is executed in Python, the default will return a none, the function can have more than one return value, if there are multiple return values, the return value will be placed in a tuple, the return is a tuple.
Why should there be a return value, because after this function is finished, its result will need to be used in the later program.
The return value in the function uses return, and the function ends immediately when it encounters a return.
def Calc (x, y):# This is the definition of a function with a return value c = x*y return c,x,y = Calc (5,6)# assigns the return result of the function to res print(res)
Vi. local variables and global variables
Local variable meaning is in the local effect, out of the scope of the variable, this variable is invalid, such as the above C is a local variable, after this function, there is no C this value
Global variables mean that the whole program is in effect, in the first definition of the program is the global variables, global variables if you want to modify in the function, you need to add the Global keyword declaration, if it is a list, dictionary and collection, you do not need to add the global keyword, directly can be modified.
Name ='Marry'#String Global Variablesnames = []#List Global Variables Print(name)Print(names)defTest ():GlobalName#changing the value of name requires the Global keywordName ='Sriba'names.append (name)#Modifying the value of a global variable names returnnames test () Call functionPrint('after modification', name)Print('names after modification', names)
Vii. Recursive invocation
Inside a function, you can call other functions. If a function calls itself internally, the function is a recursive function.
Recursive invocation means, within the function itself calls itself, a little loop meaning, write a recursive, as follows:
deftest1 (): Num= Int (Input ('Please enter a number:')) ifNum%2==0:#determine if the number entered is even returnTrue#if it is an even number, the program exits and returns True. Print('not even please re-enter! ') returnTest1 ()#if it is not even, continue calling yourself, enter the valuePrint(Test1 ())#Call Test
Characteristics of recursive invocation:
1. There must be a clear end condition
2. Each time a deeper level of recursion is reached, the problem size should be reduced compared to the previous recursion
3. Recursive efficiency is not high, too many recursive hierarchy will lead to stack overflow (in the computer, function calls through the stack (stack) This data structure implementation, each time into a function call, the stack will add a stack of frames, whenever the function returns, the stack will reduce the stack frame. Because the size of the stack is not infinite, there are too many recursive calls, which can cause the stack to overflow.
Viii. higher-order functions
What is a higher-order function, if the parameter of a function is a function, then this function is a higher-order function, said to be more ignorant, the following code to understand
defs_int (n):#The purpose of this function is to convert the passed parameter type to int type returnint (n)defAdd (x, Y, z):#The meaning of this function, to receive 3 parameters, X,y,z,z is a function Print(z (x) +z (y))#This is the execution process, where z is a function that passes the values of x and Y to Z, and then adds the two values with the return value of the Z functionAdd'8','9', S_int)#call, pass in the values of x and Y, and pass the defined function above.
Python Learning Basics-functions