Python programming (3)

zhaozj2021-02-08  235

Chapter 4 Process Control

We have seen how to run through the While Control Process. This chapter introduces more control structures. Python has a similar control structure similar to other languages ​​but slightly different.

4.1 IF statement

The IF statement may be the most basic program branch statement. E.g:

>>> IF x <0:

... x = 0

... Print 'Negative Changed to Zero'

... ELIF X == 0:

... Print 'Zero'

... ELIF X == 1:

... Print 'Single'

... Else:

... Print 'more'

...

You can have zero to multiple ELIF portions, and the else is part of the ELSE. Keyword ELIF is an abbreviation of Else IF, which can shorten the length of the speech. Switch or CASE statements in other languages ​​can be implemented with the IF ... Elif ... Elif ... statement group.

4.2 for statement

The FOR statement in Python is slightly different from the corresponding statements you might be familiar with C or PASCAL. The digital sequence is always looped like Pascal, nor is it completely controlled by programmers freely by the programmad, and Python's FOR cycle is a sequence of any kind (such as a list or string). The order is traversed for each item. E.g:

>>> # Calculate strings:

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

>>> for x in A:

... Print X, Len (X)

...

Cat 3

WINDOW 6

Defenestrate 12

>>>

Try not to modify the sequence used to control the loop within the cycle (of course, only variable sequence types such as the list may be modified) so that the program may have problems. If this is to be required, for example, some items are required, the loop can be controlled by the sequence. A fragment mark makes you easy to generate a copy:

>>> for x in a [: # Generate a clip of the entire list

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

...

>>> a

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

>>>

The result is the beginning of the list of more than 6 characters long in the list.

4.3 Range () function

If you really need to loop a column of numbers, you can use the built-in function RANGE (). It generates a list of digital sequences, such as:

>>> RANGE (10)

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

>>>

Note The end point given never appears in the generated list, and the RANGE (10) generates a 10 number list, exactly the values ​​of the legal subscript of the sequence of length 10. You can also specify different starting points, or specify different intervals (or even negative numbers):

>>> RANGE (5, 10)

[5, 6, 7, 8, 9]

>>> RANGE (0, 10, 3)

[0, 3, 6, 9]

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

[-10, -40, -70]

>>>

In order to cycle the sequence subscript, use RANGE () and len (): >>> 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 statement, continue statement and ELSE clause in the loop

Like the C language, the BREAK statement jumps out of the innermost FOR or WHILE loop to which it is, and the Continue statement continues the next loop step.

The loop statement can also bring an else clause that performs its content when the loop is ended, but does not perform its content if the loop is jumped out of the BREAK statement. The following example illustrates this usage, this example is required:

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

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

... if n% x == 0:

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

... BREAK

... Else:

... 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 not perform any operations, and use this statement when the syntax requires a statement and the program does not need to perform the operation. E.g:

>>> While 1:

... Pass # Wait for the keyboard interrupt

...

4.6 function definition

We can define all Fibonacci sequence values ​​below to calculate a certain limit:

>>> DEF FIB (N): # Write all Fibonacci sequence values ​​below n

... a, b = 0, 1

... while b

... Print B,

... a, b = b, A B

...

>>> # Call the function just defined:

... FIB (2000)

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

>>>

The keyword DEF starts a function definition, and it should be a function name, a number of references within parentheses, and ending with a colon. The various statements constituting the functional body start from the next row, and a tab is used. The first statement of the function can be a string. If so, this string is a function's document string, referred to as DOCSTRING. Some tools can automatically generate printed documents using document strings, or let the user interactively browses the code, so join the document string when programming, it is a good habit, which should develop such habits.

The function introduces a new symbol table for local variables at execution. Both variable assignments in the function are stored in a local symbol table; the variable name is quenching from the local symbol table when the reference variable is found, and then lookups from the built-in name. Therefore, the global variable cannot be assigned directly in the function (unless the Global statement is used), but the value of the global variable can be referenced. The active call of the function call is introduced into the local symbolic table of the function, that is, the parameters of the function are called by value. The function generates a new symbolic table when the function calls other functions. However, it is strictly that the call is called by reference, because if the parameter is a variable type, if the content is changed, the content changed in the function will result in the content of the argument, which is changed (not changed is the first Binding relationship).

The function definition puts the function name into the current symbol table. The value type of the function name is a user-defined function. This value can be assigned to another name, so this name also represents the same function. This can be used as a general change method:

>>> FIB

>>> f = FIB

>>> f (100)

1 1 2 3 5 8 13 21 34 55 89

>>>

You may say that FIB is not a function but the process. Like Python and C, the process is just a function that does not return values. In fact, strictly said that the process returns a value, just a very inexpected value. This value is called None (this is a built-in name). If the program is interactive, if you only need to display this value, it will be ignored. If you want to display it, you can use a Print statement:

>>> Print FIB (0)

None

>>>

You can also write a function to return a numeric list of the Fibonacci sequence rather than display these values:

>>> DEF FIB2 (N): # Return until n Fibonacci sequence value

... result = []

... a, b = 0, 1

... while b

... result.Append (b) # Explanation

... a, b = b, A B

... Return RESULT

...

>>> F100 = FIB2 (100) # call

>>> F100 # output result

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

>>>

This example also demonstrates a new Python feature: Return statement exits from the function and returns a value. Return without the return value can exit from the middle of the process, and can be exited at the end of the process, and NONE is returned in both cases.

Statement Result.Append (b) call a method of the list object Result. The method is "a function of an object, the reference format is obj.MethodName, where OBJ is an object (also allowed to be an expression), and methodname is a method of defining the type of object. Different methods. Different types of methods can use the same name without causing misunderstanding. (You can define your own object types and methods, using classes, this topic will be discussed later). The method of listing the object when the Append () method in the example is added, which adds a new element at the end of the list. In this example, this is equivalent to "Result = Result [B]", just more effective.

4.7 Function parameters

You can define a function that uses a variable number parameter. There are three such definition methods that can be used in combination. 4.7.1 Parameter default

You can specify the default value for a parameter or several parameters. This definition function can be quite a fewer numbers when calling. E.g:

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

While 1:

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 call both: ask_ok ('do you real want to quit?'), Or can call: ask_OK ('Ok to overwrite the file?', 2). The default is calculated in the defined scope during the function definition, for example:

i = 5

DEF F (arg = i): Print Arg

i = 6

f ()

5 will be displayed.

Note: The default value is only calculated. This is noteworthy when the default value is a variable object such as a list or a dictionary. For example, the following functions will be added in the future call:

DEF F (A, L = []):

L.Append (a)

Return L

Print f (1)

Print f (2)

Print f (3)

This Will Print

[1]

[1, 2]

[1, 2, 3]

If you don't want the default value being reserved in a continuous call, you can write functions below this:

DEF F (a, l = none):

IF l is none:

l = []

L.Append (a)

Return L

4.7.2 Keyword Parameters

When the function is called, you can also specify the acts such as "Keyword = Value", where the keyword is the name of the shape used when defined. E.g:

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 as follows:

Parrot (1000) # Default

PARROT (Action = 'VOOOOM', VOLTAGE = 1000000) # keyword, default, order variable

Parrot ('a thousand', state = 'pushing up the daisies') # position parameters, default, keyword

Parrot ('a million', 'bereft of life', 'jump') # position parameters, default, but the following types of call modes are wrong:

Parrot () # Non-default parameters are not available

Parrot (Voltage = 5.0, 'dead') # There is a non-keyword parameter after the keyword parameter

Parrot (110, Voltage = 220) # parameter value is re-supplied

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

Generally speaking, the positional parameters in the table are in front, the keyword parameter is behind, the keyword name must be a shape parameter. The shape may be called in the form of a keyword parameter without default. Each shape can only correspond to a corresponding argument, so the ginseng of the incoming value of the position parameter cannot be used as a keyword parameter in the same call.

If there is a shape in which the shape is ** Name, this form parameter can receive a dictionary when calling, and the dictionary contains all keyword parameters that are not matched with any gates. A special, * name-based ginseng, which will accept all the prefaces composed of all positional parameters that cannot be matched. * Name can only appear before ** Name. For example, if the following function is defined:

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 Arg

PRINT '-' * 40

For kw in keywords.keys (): Print Kw, ':', keywords [kW]

You can call this:

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

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

Client = 'John Cleese',

Shopkeeper = 'Michael Palin',

Sketch = 'Cheese Shop Sketch')

The results show that:

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

4.7.3 Arbitrary number parameters

There can be two special ginseng after all the famous ginseng, one named in the form of * args, named in the form of ** kW. With the form of the * args form, you can enter any number of parameters after the normal matching real-than-reference table, which makes a program to assign the Args-form parameter and cannot match the keyword parameters. Make up a dictionary to KW meticulum. There are 0 to multiple normal parameters before any number of ginseng. E.g:

DEF FPRINTF (File, Format, * Args):

File.write (Format% Args)

4.7.4 Lambda form

Because many people's requirements, some of the functions common to function programming languages ​​and LISP are added to Python. You can define a small non-name function with a lambda keyword. This is a function that returns two parameters: "Lambda A, B: A B". Lambda forms can be used in any place where functions are required. LAMBDA form is limited to an expression from the syntax. From a semantic, this is just a normal function defined syntax sweet. Like a nested function definition, the lambda form cannot access variables contained in the scope they defined, but can be cautiously use the default parameters. This limit can be bypassed. E.g:

Def make_incrementor (N):

Return Lambda X, Incr = N: X InCr

4.7.5 Document String

About the content and format of the document string are forming some practices. The first line should be summarized for a short object purpose. For the sake of brevity, this line should not mention the name or type of the object, as these can be learned by other ways (of course, if the object name is a verb description function operation, it is of course mentioned). With the line, you should start with a number of letters, ending with the sentence. If there are multiple lines in the document string, the second line should be blank, separated from other instructions. The following rows can be a paragraph or several paragraphs, describing the calling method of the object, its side effects, and so on.

Python's scanner does not remove indentation blank from multi-row strings, so the tool for handling documents requires yourself to process indentation. As long as the following conventions can be conducive to indenting blank processing. The first non-blank row after the first line determines the amount of indented the entire document string (we don't have to use the first line because it is often directly following the quotation marks beginning with the string). Document strings are deleted with blank equivalent to this row. The table will be extension to delete it after the table.

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

New Post(0)