This chapter describes how to organize statements into functions, which can tell computers how to do things.
Write a short section belowCodeCalculate the sequence of two orders (the sum of the first two is the third number)
fibs = [008000] # define a list with the initial content of 0, 1 for I in range (8): # loop 8 times fibs. append (FIBS [-2] + fibs [-1]) # append a number at the end, which is the sum of the first two values # input >> fibs # output [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Because the value is assignedFibsThere are already two numbers (0,1), So the loop8After, the List has10Number. The sum of the two numbers is equal to3Number.
Do you think we should use the input to control the number of prints? Only useProgramJust a little change.
Fiber = [0, 1] Num= Input ('How many Fibonacci numbers do you want?')ForIInRange (num-2): Fiber. append (fiber [-2] + fibs [-1])PrintFibs#Input>>>How many Fibonacci numbers do you want?12#Output[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Abstraction
Abstract can save a lot of work, which makes computer programs easy to understand. Computers like to process precision and specific commands, but people are different. We prefer to drop in something and the computer can give us the desired results, instead of telling it how to do it step by step. Therefore, the above Code is abstracted like this:
Num = input ('How many Fibonacci numbers do you want?')PrintFibs
Then how does the computer know how to do it? We can encapsulate the processing process as a function. We can only call this function every time we use it.
Create a function
A function can be called. It executes an action and returns a value. Built-inCallableA function can be used to determine whether a function is callable:
>>>ImportMath>>> X = 1 >>> y =Math. SQRT>>>Callable (x) False>>>Callable (y) True
Note:CallableInPython3.0Is no longer available.
How can we define a function? UseDefStatement:
>>> Def Hello (name ): Return ' Hello. ' + Name + ' ! ' # We have defined a hello function, which will add "hello." Before the input content and "!", And return # User >>> Print Hello ( ' World ' ) Hello. World! >>> Print Hello ( ' Zhangsan ' ) Hello. zhangsan!
great! Let's go back and think about how to define a function to return the sequence of returns.
#Defines the fibs function, which is used for the Na-Qi series.>>>DefFibs (Num): Result= [0, 1]ForIInRange (num-2): Result. append (result [-2] + result [-1])ReturnResult#Directly call the fibs Function>>> Fiber (10) [0,1, 1, 2, 3, 5, 8, 13, 21, 34]>>> Fiber (15) [0,1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,144,233,377]
Local variable
When a function defines a life variable, the change of life in the function is valid only in the function. It has nothing to do with other variables with the same name as the function.
# Local variable Def Func (x ): Print ' X is ' , X = 2 # X = 2 only works in the func Function Print ' Changed local X ' , X = 50 Func (X) # The func function does not return data. Print ' X is still ' , X # Output >>>X Is 50 Changed local X 2 X Is Still 50
GlobalStatement
If you want to name a variable as global, you can useGlobalStatement.
Def Func (): Global X Print ' X is ' , X = 2 Print ' Changed local X ' , Xx = 50 Func () Print ' Value of X is ' , X # Output X Is 50 Changed local X 2 Value of X Is 2
GlobalStatement is used for lifeXIs global.FuncAfter the function,XThe value has changed and acts on the entire program. Therefore, the final input result is2
Default parameters
For some parameters, we want some of them to be optional. If you do not want to provide values for these parameters, these parameters use the default values.
DefSay (message, Times = 1):PrintMessage *Timessay ('Hello') Say ('World', 5)#Output>>>Helloworldworldworldworld
DefinedSayThe second parameter of the function is optional. The default value isTimes = 1That is, the output is multiplied by two parameters.
Note: Only the parameters at the end of the form parameter table can have default parameters, suchDef func (A = 5, B)Is invalid.
Key parameters
If a function has many parameters and we only want to specify a part of them, you can specify real parameters for the function by name (keyword) instead of location.----This is called a key parameter.
Def Func (a, B = 5, c = 10 ): Print ' A is ' ,, ' And B is ' , B, ' And C is ' , Cfunc ( 3, 7 ) Func ( 24, c = 32 ) Func (C = 23, A = 14 )
# Output >>> A Is 3And B Is 7 And C Is 10 A Is 24 And B Is 5 And C Is 32 A Is 14 And B Is 5And C Is 23
In this way, I don't have to worry about the order of parameters, so it is easier to use functions. If other functions have default values, we can only assign values to the parameters we want.
Recursion:
Useful recursive functions...Wait, what is useless recursion? Let's first look at the definition of a function:
DefRecursion ()ReturnRecursion ()
Obviously, it can't do anything. Program Execution keeps applying for memory, directly exhausting the memory, and the program crashes.
Then, a useful recursive function contains the following parts:
- Basic instances (minimum possibility) when the function returns values directly)
- Recursive instances include recursive calls of the smallest part of one or more problems.
The following uses recursive functions to calculateNLevel,N * (n-1) * (n-2) *... * 1
DefF (n ):IfN = 1:Return1Else:ReturnN * F (n-1)