First write an example -- generate the number of Fibonacci within N:
Def fib (n ):
A, B = 0, 1
While B <n:
Print B,
A, B = B, A + B
Def points out that the following part is a function. Similar to C, Python does not distinguish between a process (no return value) and a function (with a return value ). As strictly stated above, it is a process (procedure ).
For a project, it is necessary to insert a concise and clear description text in the code of different modules. Python supports syntax similar to Java-Doc. For example:
Def fib (n ):
"Print a maid series up to n ."""
A, B = 0, 1
While B <n:
Print B,
A, B = B, A + B
Place the description text between a pair of "" (three quotation marks). Some document generation tools extract the text to generate documents such as HTML and latex. Writing these texts does not take much time. It is absolutely advantageous to develop this habit.
Function calls are also very simple. For the above, you only need to directly use fib (100) to generate the corresponding output: 1 1 2 3 5 8 13 21 34 55 89
Functions can also be referenced. For the defined fib, F = fib means that f references the FIB function. Now these two names refer to the same thing. So we can use it like this: >>> F (100)
The output result is the same as the preceding one. It can be understood by following the "function pointer" in C language.
Although Python functions can not explicitly write return statements, in fact, such functions will return a special value of none. For example, there is a function that does nothing:
Def fun ():
Pass
You can use print in the interpreter to display its value: >>> print fun ()
None
Now we can transform the above fib function so that it will not directly generate output, but will generate a list of the Fibonacci series: def fiber 2 (n ):
"Print a finonacci series up to n ."""
A, B = 0, 1
Result = []
While B <n:
Result. append (B)
A, B = B, A + B
Return result
Append is a method of the List class, that is, adding elements to a list. The result of this function is as follows: >>> print fiber 2 (100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Default parameters
Python functions support default parameters. You can define a function with two parameters, but you can only tell one or none of them when calling it-as long as you specify the default value of the parameter during the definition. This is like learning from C ++.
Def ask_ OK (prompt, retries = 4, complaint = 'yes or no, please! '):
While true:
OK = raw_input (prompt)
If OK in ('y', 'Ye ', 'yes'): Return true
If OK in ('n', 'No', 'nop', 'nope'): Return false
Retries = retries-1
If retries <0: Raise ioerror, 'refusenik user'
Print complaint
In this way, there are multiple calling methods: >>> ask_ OK ('Do you really want to quit? ')
>>> Ask_ OK ('Do you really want to quit? ', 2)
>>> Ask_ OK ('Do you really want to quilt? ', 3,' What do you want to do? ')
The default value of the parameter is determined at the entry of the function when it is defined. This can be explained through an experiment: I = 5
Def F (ARG = I ):
Print ARG
I = 6
F ()
It is found that the output is 5 rather than 6, because the later I changes will not affect the ARG in the function.
Note that the default parameters of a function are calculated only once. In this way, if the default parameter is a composite type (list, String, class), a "accumulation effect" may occur:
Def f (a, L = []):
L. append ()
Return L
If three times are called:> Print F (1)
[1]
>>> Print F (2)
[1, 2]
>>> Print F (3)
[1, 2, 3]
To avoid this problem, you must explicitly set the default value of L to none in the defined parameter list:
Def f (a, L = none ):
If l is none:
L = []
L. append ()
Return L
Parameters with keywords
The keyword can be interpreted as the name of the function header parameter. By specifying a keyword when calling a function, you can pass the parameter value in different sequence defined by the parameter. Def parrot (voltage, state = 'a stiff ', Action = 'voom', type = 'Norwegian Blue '):
Print "-- this parrot wouldn't", action,
Print "If you put", voltage, "volts through it ."
Print "-- lovely plumage, the", Type
Print "-- it's", state ,"! "
Call with keywords: parrot (1000)
Parrot (Action = 'vooom ', voltage = 1000000)
Parrot ('a thousand', state = 'pushing up the daisies ')
Parrot ('a million', 'bereft of life', 'jump ')
The following call methods are incorrect: parrot () # The specified parameter is missing.
Parrot (voltage = 5.0, 'Demo') # No keyword is specified
Parrot (110, voltage = 220) # Pass repeated Parameters
Parrot (actor = 'John Cleese ') # non-existent keywords
More flexible, you can use * name or ** name to represent uncertain parameters or parameters with keywords (dictionary) when defining a function ). This example is easy to understand:
Def cheeseshop (kind, * arguments, ** keywords ):
Print "-- do you have any", kind ,'? '
Print "-- I'm sorry, we're all out of", kind
For ARG in arguments: Print ARG
Print '-' * 40
Keys = keywords. Keys ()
Keys. Sort ()
For kW in keys: Print kW, ':', keywords [kW]
You can call the cheeseshop ('limburger ', "It's very runny, sir. "," it's really very, very runny, sir. ", client = 'John Cleese ', shopkeeper = 'Michael Palin', sketch = 'cheese shop sketch ')
The result is: -- do you have any Limburger?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, very runny, sir.
----------------------------------------
Client: John Cleese
Shopkeeper: Michael Palin
Sketch: cheese shop sketch
You can also use list to pass multiple parameters. The elements in the list are separated and called unpack. This is done by the python interpreter behind the scenes. For example, the range function can specify two parameters, which can constitute a list, and then pass the list: >>> ARGs = [3, 6]
>>> Range (* ARGs) # Call with arguments unpacked from a list
[3, 4, 5]
Similarly, you can use the ** operator to pass a dictionary, which corresponds to the method for passing parameters with keywords. >>> Def parrot (voltage, state = 'a stiff ', Action = 'voom '):
... Print "-- this parrot wouldn't", action,
... Print "If you put", voltage, "volts through it .",
... Print "E's", state ,"! "
...
>>> D = {"voltage": "four million", "State": "bleedin 'demised", "action": "voom "}
>>> Parrot (** D)
-- This parrot wouldn't voom if you put four million volts through it. e's bleedin 'demised!
Understanding with your heart.
Lambda Functions
Python learns this function from the function language. A Lambda function is an anonymous function that functions like a function template and can be used to generate other functions conveniently. Lambda functions need to be understood more. Just take a few examples: >>> def make_incrementor (n ):
... Return Lambda X: x + n
...
>>> F = make_incrementor (42)
>>> F (0)
42
>>> F (1)
43