Python Guide - In-depth process control

zhaozj2021-02-11  236

This section

4.1 IF statement 4.2 for statement 4.3 Range () Function 4.4 Break and Continue statement, and ELSE clause 4.5 PASS statement in loops 4.6 Definition function 4.7 In-depth function definition

4.7.1 Parameter defaults 4.7.2 Parameter Keyword 4.7.3 Variable Parameter Table 4.7.4 Lambda Form 4.7.5 Document String

? 4. Other process control tools

In addition to the While statement described earlier, Python also borrowed some process control functions from other languages ​​and changed.

? 4.1 IF statement

Perhaps the statement type of the most sentence is an IF statement. E.g:

>>> x = int (Raw_Input ("please enter an integer:"))

>>> IF x <0:

... x = 0

... Print 'Negative Changed to Zero'

... ELIF X == 0:

... Print 'Zero'

... ELIF X == 1:

... Print 'Single'

... Else:

... Print 'more'

...

There may be 0 or many ELIF portions, and ELSE is optional. Keyword "Elif" is an abbreviation for "else if", which can effectively avoid excessive indentation. If ... ELIF ... Elif ... Sequence is used to replace Switch or CASE statements in other languages.

? 4.2 for statement

The for? Statement in Python is slightly different from you in C or PASCAL. The usual loop may define an equivalence step step process (such as pASCAL) or by the user to define iterative steps and abort conditions (such as c), Python's for? Statement in accordance with the child in any sequence (linked list or string) , Iterates according to their order in the sequence. For example (no fencing):

>>> # Measure Some Strings:

... a = ['Cat', 'Window', 'DefenestRate']

>>> for x in A:

... Print X, Len (X)

...

Cat 3

WINDOW 6

Defenestrate 12

Modify the iterative sequence insecure during iteration (such a case only when using a variable sequence such as a linked list). If you want to modify the sequence of your iteration (for example, copy the selection), you can iterate its replica. This usually uses a slice identification to make this:

>>> for x in a [: # Make a SLICE COPY OF THE ENTIRE LIST

... if len (x)> 6: a.insert (0, x)

...

>>> a

['Defenestrate', 'Cat', 'Window', 'DefenestRate']

? 4.3 Range () functions

If you need a numeric sequence, the built-in function range () may be useful, it generates an equal line-of-one linked list.

>>> RANGE (10)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Range (10) Generates a linked list containing 10 values. Its accurate use of the index value of the list filled this length of 10, which does not include end values ​​in the range in the generated linked list. Also allow the RANGE operation to start from another value, or you can specify a different step value (even negative, sometimes this is also called "step length"): >>> Range (5, 10)

[5, 6, 7, 8, 9]

>>> RANGE (0, 10, 3)

[0, 3, 6, 9]

>>> RANGE (-10, -100, -30)

[-10, -40, -70]

If you need iteratory table index, use RANGE () and LEN () as shown below:

>>> a = ['Mary', 'Had', 'A', 'Little', 'Lamb']

>>> for i in range (len (a)):

... Print I, A [I]

...

0mary

1 had

2 a

3 Little

4 lamb

4.4 BREAK and Continue statements, and ELSE clauses in the loop

A similar to C is used to jump out of the nearest level for or while loop.

The Continue statement is known from C, which means that the loop continues to perform the next iteration.

The loop can have an ELSE clause; it is executed when a full list (for for for for) or performing the condition is false (for while), but is not performed in the case where the loop is aborted by BREAK. The sample program of the following search prime number demonstrates this clause:

>>> for N in Range (2, 10):

... for x in Range (2, n):

... if n% x == 0:

... Print N, 'Equals', X, '*', N / X

... BREAK

... Else:

... # loop fell through without finding a factory

... Print N, 'Is a Prime Number'

...

2 is a principle Number

3 is a principle Number

4 Equals 2 * 2

5 is a principle Number

6 Equals 2 * 3

7 is a principle Number

8 Equals 2 * 4

9 Equals 3 * 3

? 4.5 PASS statement

The PASS statement does nothing. It is used in those statements that must have, but don't do anything on the program, for example:

>>> While True:

... Pass # busy-wait for keyboard interrupt

...

? 4.6 Define functions

We can write a function to generate a Mippi-Cilia with a given upper industry:

>>> DEF FIB (N): # Write Fibonacci Series Up to n

... "" "" PRINT A FIBONACCI Series Up to n. "" ""

... a, b = 0, 1

... while b

... Print B,

... A, B = B, A B ...

>>> # Now call the function we need jud defined:

... FIB (2000)

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

Keyword DEF introduces a function definition. In response, there must be a function name and a parentheses including the formal parameters. The function state statement begins with the next line, it must be indent. The first line of the function body can be a string value. This string is the function of the document string, or it can be called DOCSTRING. ?

Some document string tools can process or print documents online, or browse the code to the user interact; adding a document string in your code, it is a good practice.

When the function is called, a new symbol table is introduced for a local variable. All local variables are stored in this partial symbol table. When references parameters, you will look up from the local symbol table, then the global symbol table, then the built-in naming table. Therefore, although global parameters can be referenced, they cannot directly assign (unless they are named using Global statements).

The actual parameter of the function reference is introduced into the local symbol table when the function call is called. Therefore, the actual parameter is always transmitted (the value here is always a object reference, not the value of the object). 4.1 When a function is called by another function, a new local symbol table is created during the calling process.

The function is defined in the current symbol table to introduce a function name. As a user-defined function, the function name has a type value approved by the interpreter. This value can assign other named so that it is used as a function. This is like a rename mechanism:

>>> FIB

>>> f = FIB

>>> f (100)

1 1 2 3 5 8 13 21 34 55 89

You may think FIB is not a function, but a process (Procedure). Python and C are just a function that does not have a return value. In fact, from the technical process, there is also a return value, although it is not a discussion. This value is called None (this is a built-in naming). If a value is just none, the usual interpreter will not write a none, if you really want to see it, you can do this:

>>> Print FIB (0)

None

The following is demonstrated how to return a value of the Numerical chain containing the Philippine desence in the function instead of printing it:

>>> DEF FIB2 (N): # Return Fibonacci Series Up to N

... "" "" Return a List Containing The Fibonacci Series Up to n. "" "

... result = []

... a, b = 0, 1

... while b

... Result.Append (b) # See Below

... a, b = b, A B

... Return RESULT

...

>>> F100 = FIB2 (100) # Call IT

>>> F100 # Write the result

[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

As before, this example demonstrates some new Python features: return statement returns a value from the function, and returns NONE without an expression. The process will return none after the end. Statement Result.Append (b) is a method for Lin table object Result. The method is a "function of" a "one object, which is named obj.methodename, where the OBJ is an object (may be an expression), MethodeName is a naming of a method in the object type definition. Different types of methods define different methods. Different types may have the same name, but will not be confused. (This may happen when you define your object types and methods, this guide will introduce how to use classes). The Append () method shown in the example is defined by a linked list object, which adds a new element to the linked list. In the example, it is equivalent to "Result = Result [B]", but it is more efficient.

? 4.7 In-depth function definition

Sometimes you need to define a variable number of parameters. There are three ways to do, and we can use them in combination.

? 4.7.1 parameter default value

The most useful form is to specify the default value for one or more parameters. This created function can use fewer parameters when calling.

Def ask_ok (prompt, retries = 4, complaint = 'yes or no, please!'):

While True:

OK = Raw_INPUT (Prompt)

IF OK IN ('Y', 'Ye', 'Yes'): Return 1

IF OK in ('N', 'NO', 'NOP', 'NOPE'): Return 0

RETRIES = Retries - 1

If Retries <0: Raise IoError, 'Refusenik User'

Print Complaint

This function can also be called in the following ways: Ask_ok ('Do You Really Want To Quit?'), Or like this: Ask_ok ('Ok To Overwrite THE?', 2).

The default value is parsed in the function definition segment, as shown below:

i = 5

DEF F (arg = i):

Print Arg

i = 6

f ()

Will Print 5.

Important warning: The default value will only be parsed once. Some differences are generated when the default is a variable object, such as a chain table, a dictionary or most class instance. For example, the following function accumulates its parameter value in successive calls:

DEF F (A, L = []):

L.Append (a)

Return L

Print f (1)

Print f (2)

Print f (3)

This will be printed:

[1]

[1, 2]

[1, 2, 3]

If you don't want to share parameter default values ​​between different function calls, you can write functions as the following instance:

DEF F (a, l = none):

IF l is none:

L = []

L.Append (a)

Return L

? 4.7.2 Parameter keyword

The function can be called by the form of the parameter keyword, such as "Keyword = Value". For example, the following functions:

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, "!"

You can call any of the following methods:

Parrot (1000)

Parrot (action = 'voooom', Voltage = 1000000)

PARROT ('a thousand', state = 'pushing up the daisies')

Parrot ('a million', 'bereft of life', 'jump')

However, the following calls are invalid:

Parrot () # Required Argument Missing (missing required parameters)

Parrot (Voltage = 5.0, 'DEAD') # Non-Keyword Argument Following Keyword (Non-keyword parameters behind the keyword)

Parrot (110, Voltage = 220) # duplicate value for argument (repeated assignment to parameters)

Parrot (actor = 'john cleese') # unknown keyword (unknown keyword)

Typically, each keyword in the parameter list must come from a form parameter, and each parameter has a corresponding keyword. The default value is not important if the form parameter is not important. Actual parameters cannot assign multiple values ​​at a time - form parameters cannot be used in the same call simultaneously using location and keyword binding values. Here is an example to demonstrate the failure of this constraint:

>>> DEF FUNCTION (A):

... Pass

...

>>> Function (0, a = 0)

TRACEBACK (MOST RECENT CALL LAST):

File "

", LINE 1, IN?"

TypeError: function () got multiple value for keyword argument 'a'

When a form of parameters such as ** Name, it receives a dictionary that contains all keyword parameters that have not appeared in the form parameter list. A form of form parameters such as * name may also be used here, which receives a topology (described in detail in the next section), containing all parameter values ​​that do not appear in the form parameter list. (* Name must appear before ** Name), for example, we define a function:

DEF Chezeeshop (Kind, * Arguments, ** keywords):

Print "- do you have any", kind, '?'

Print "- I'm Sorry, We're All Out of", Kind

For arg in arguments: print argprint '-' * 40

Keys = keywords.keys ()

Keys.sort ()

For kw in keys: Print Kw, ':', Keywords [kW]

It can call like this:

Chezeeshop ('Limburger', "IT's Very Runny, Sir.",

"It's really, very rueny, sir.",

Client = 'John Cleese',

Shopkeeper = 'Michael Palin',

Sketch = 'Cheese Shop Sketch')

Of course, it will print as follows:

Do you have any limited?

- I'm Sorry, We're All Out of Limburger

IT's Very Runny, SIR.

IT's really, Very Runny, SIR.

----------------------------------------

Client: John Cleese

SHOPKEEPER: Michael Palin

Sketch: Cheese Shop Sketch

Note that the sort () method is called before the keyword dictionary content printing, otherwise, the order of printing parameters is undefined.

? 4.7.3 variable parameter table

Finally, a least commonly used option is to allow function to call a variable number of parameters. These parameters are packaged into a topology. Before these variable number of parameters, there can be zero to multiple ordinary parameters:

DEF FPRINTF (File, Format, * Args):

File.write (Format% Args)

? 4.7.4 lambda form

For appropriate needs, there are several features that are usually added in the function language and LISP to Python. With the lambda keyword, you can create a small anonymous function (who can tell me, how can this anonymous function? - Translator) Here is a function returns its two parameters: "Lambda A, B: A B ". Lambda forms can be used for any function objects required. For grammar restrictions, they can only have a separate expression. Semantics, they are just a syntax skill in the normal function definition. Similar to the nested function definition, the lambda form can reference variables from the included range:

>>> DEF MAKE_INCREMENTOR (N):

... RETURN LAMBDA X: X N

...

>>> f = Make_incrementor (42)

>>> f (0)

42

>>> f (1)

43

? 4.7.5 Document string

Here you introduce the concepts and formats of the document string.

The first line should be an introduction to the use of an object. Short start, do not have to clearly state the object name or type because they can be learned from other ways (unless this name is happening to describe the verb described). This line should start with a capital letter and end with the end.

If the document string has multiple lines, the second line should be empty, which is clearly separated from the next detailed description. The next document should have one or more paragraphs describing the call agreement, boundary effect, etc.

Python's interpreter does not remove indentation from a multi-line document string, so it should be cleared by it if necessary. This is in line with the usual habits. The first non-empty line after the first line determines the indentation format of the entire document. (We don't have to use the first line because it is usually tightly relying on the starting quotation marks, the indentation format is unclear.) Dosing white "equivalent" is the start of the string. Each line should not have indentation. If there is indent, all whites should be cleared. It is equivalent to the blank is the test after verification (usually 8 spaces). (This paragraph is translated, there is a question of readers, please refer to the original - translator) The following is an example of multi-line document string:

>>> DEF my_function ():

... "" "" "Do Nothing, But Document IT.

...

... no, real, it doesn't do anything.

... "" ""

... Pass

...

>>> print my_function .__ doc__

Do Nothing, but document it.

NO, Really, It Doesn't do anything.

footnote

... object).

4.1

In fact, it is said

Call object references are more appropriate because if you are incorporated into a variable object, the caller can get any changes generated by the caller (inserted into the subkey).

转载请注明原文地址:https://www.9cbs.com/read-4587.html

New Post(0)