Python Learning (3)-Deep Process Control

Source: Internet
Author: User
Tags case statement

If language
Perhaps the most famous statement type is the IF statement. For example
x = Int (input ("Please enter an integer:"))
Please enter an integer:42
If x < 0:
... x = 0
... print (' negative changed to zero ')
... elif x = = 0:
... print (' Zero ')
... elif x = = 1:
.. print (' single ')
.. else:
.. print (' more ')
...
More
There may be 0 to more elif sections, and else is optional. The keyword ' elif ' is an abbreviation for ' else if ', which effectively avoids too deep indentation. If ... elif elif ... A sequence is used to replace a switch or case statement in another language.

For statement
The For statement in Python is slightly different from C or Pascal. The usual loops may be based on a linear numeric step process (such as Pascal), or the user defines the iteration step and the abort condition (such as C), and the Python for statement iterates over the subkeys in any sequence (linked list or string) in the order in which they are in the sequence. For example (no allusion):

# Measure Some strings:
... words = [' cat ', ' window ', ' defenestrate ']
For W in words:
... print (W, Len (w))
...
Cat 3
Window 6
Defenestrate 12
It is unsafe to modify the iteration sequence during the iteration (only if a mutable sequence such as a linked list is used). If you want to modify the sequence of your iteration (for example, to copy a selection), you can iterate over its copy. It is easy to do this with the cut logo
For W in words[:]: # Loop over a slice copy of the entire list.
... if Len (w) > 6:
... words.insert (0, W)
...
Words
[' Defenestrate ', ' Cat ', ' window ', ' defenestrate ']
Range () function
If you need a numeric sequence, the built-in function range () is handy, and it generates a arithmetical progression linked list:

For I in range (5):
... print (i)
...
0
1
2
3
4
A range (10) generates a linked list of 10 values populated with the index value of the linked table with a 10-length listing, which does not include the end value in the range. You can also let the range operation start with another value, or you can specify a different step value (even a negative number, sometimes called a "step")

Range (5, 10)
5 through 9

Range (0, 10, 3)
0, 3, 6, 9

Range (-10,-100,-30)
-10,-40,-70
If you need to iterate the linked list index, use range () and Len () as shown below

A = [' Mary ', ' had ', ' a ', ' little ', ' lamb ']
For I in range (Len (a)):
... print (i, a[i])
...
0 Mary
1 had
2 A
3 Little
4 Lamb
However, the enumerate () can be conveniently used on this occasion, see looping techniques cycle tips.

Strange things happen if you just print a sequence:

Print (range (10))
Range (0, 10)
In different ways the range () function returns an object that behaves as if it were a list, but in fact it is not. When you iterate over it, it is an object that can return successive items like the desired sequence, but it does not really construct the list in order to save space.

We call such objects to be iterative, that is, to be a target (parameter) of a function or structure that expects to get successive entries from something to the end. The For statement we have seen is such an iterator. The list () function is another (iterator) that creates lists from an iteration (object):

List (range (5))
[0, 1, 2, 3, 4]
Later we will see more functions that return an iterative (object) and an iterative (object) as an argument.

Break statements and continue statements, and ELSE clauses in loops
The break statement, like in C, is used to jump out of the nearest first level for or while loop.

A loop can have an ELSE clause, which executes when the loop iterates through the entire list (for a) or when the execution condition is false (for the while), but the loop is not executed when the break is aborted. The following example program for searching prime numbers demonstrates this clause:

For n in range (2):
... for x in range (2, N):
... if n% x = = 0:
... print (n, ' equals ', X, ' * ', n//x)
... br Eak
... else:
... # loop fell through without finding a factor
... print (n, ' is a prime number ')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 are a prime number
6 equals 2 * 3
7 is a P Rime number
8 equals 2 * 4
9 equals 3 * 3
(yes, this is the correct code.) Look carefully: The Else statement is part of the For loop, not the IF statement.)
When a loop is used, the ELSE clause has more in common with the ELSE clause of the try statement than it does if the statement is: an else clause of the a try statement, no exception runs, and no interruption occurs when the ELSE clause of a loop occurs. For more information about try statements and exceptions, handle exceptions. The
Continue statement is a reference from C, which indicates that the loop continues to perform the next iteration:

For NUM in range (2, 10):
If num% 2 = = 0:
.. print ("Found An even number", num)
... continue
... print ("Found a number", num)
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9
Pass Statement
The pass statement does nothing. It is used for situations where the syntax must have a statement, but the program does nothing, such as:

While True:
... pass # busy-wait for keyboard interrupt (CTRL + C)
...
This is typically used to create a class with minimal structure

Class Myemptyclass:
... pass
...
On the other hand, pass can be used as a placeholder for a function or control body when creating new code. Allows you to think at a more abstract level. Pass can be neglected silently:

def initlog (*args):
... pass # Remember to implement this!
...
Defining functions
We can define a function to generate an arbitrary upper bound of the Fibonacci sequence.

def fib (n): # write Fibonacci series up to N
... "" "Print a Fibonacci series up to N." "" "
... a, b = 0, 1
... while a < n:
... print (A, end= ")
... a, B = B, a+b
... print ()
...
# now call the function we just defined:
... fib (2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
The keyword def introduces a function definition. Must be followed by a function name and parentheses that include formal parameters. The function body statement starts from a line and must be indented.

The first line of the function body can be a string value, which is the function's document string, or DocString. (a more progressive document string describes the documentation Strings () document string that can be found in this section.) Some tools use a document string to generate and print documents online, or to allow users to interactively navigate through code, and to write code into a document string is a good style and should form a habit.

A new symbol table is introduced for local variables when the function is executed. All local variables are stored in this local symbol table. When a parameter is referenced, it is first looked up from the local symbol table, then the global symbol table, and then the built-in named table. As a result, global parameters can be referenced, but they cannot be directly assigned in the function (unless they are used with the global statement name).

The actual argument of the function reference introduces a local symbol table when the function is called, so the argument is always called (the value is always an object reference, not the value of the object) [1] When a function is called by another function, a new local symbol table is created during the call.

The function definition introduces the function name in the current symbol table. As a user-defined function, the function name has a type value that is recognized by the interpreter. This value can be assigned to other names so that they can be used as a function. It's like a renaming mechanism

Hi

f = fib
F (100)
0 1 1 2 3 5 8 13 21 34 55 89
You might think that FIB has no return value, it is not a function, but a procedure (procedure). In fact, even if the function does not have a return statement, it has a return value, although it is a less pleasing one. This value is called None (this is a built-in name). If a value is just None, the interpreter will usually not write it, and if you really want to see it, you can do it.

FIB (0)
Print (fib (0))
None
It is very simple to define a function that returns a list of Fibonacci numbers 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 a < n:
... result.append (a) # see below
... a, B = B, a+b
... return result
...
F100 = Fib2 (+) # call it
F100 # Write The result
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
As before, this example demonstrates some of the new Python features: The return statement returns a value from the function, and return without an expression returns none. None will be returned when the process is finished.
Statement Result.append (b) a method called result of a linked list object. The method is a function that belongs to an object that is named Obj.methodename, where obj is an object (possibly an expression), and Methodename is the name of a method in that object type definition. Different types define different methods. Different types may have the same name method, but will not be confused. (This can happen when you define your own object types and methods, as defined by class, as described in 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 more efficient.

Deep function definition
In Python, you can also define functions that contain several parameters. There are three available forms and can be used in combination.

Default parameter values

One of the most common forms is specifying a default value for one or more parameters. This creates a function that can be called with fewer parameters than is allowed at the time of definition, for example:

def ask_ok (prompt, retries=4, complaint= ' Yes or No, please! '):
While True:
OK = 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 OSError (' uncooperative user ')
Print (complaint)
This function can be called in several different ways: only the necessary parameters are given: ASK_OK (' Do you really want to quit? ')
An optional parameter is given: Ask_ok (' OK to overwrite the file? ', 2)
Or give all the parameters: Ask_ok (' OK to overwrite the file? ', 2, ' Come on, only yes or no! ')

This example also describes the in keyword. It determines whether a certain value is included in the sequence.
The default value is resolved at the function definition scope, as follows:

i = 5

def f (arg=i):
Print (ARG)

i = 6
F ()
The output will be 5.

Important WARNING: The default value is only assigned once. This makes it different when the default value is a Mutable object, such as a list, a dictionary, or an instance of most classes. For example, the following function accumulates (before) the arguments passed to it during subsequent calls:

Def f (A, l=[]):
L.append (a)
Return L

Print (f (1))
Print (f (2))
Print (f (3))
This will output:

[1]
[1, 2]
[1, 2, 3]
If you do not want the default values to accumulate in subsequent calls, you can define the function as follows:

Def f (A, L=none):
If L is None:
L = []
L.append (a)
Return L
Keyword parameters

Functions can be called in the form of keyword arguments keyword argument, such as Kwarg=value. For example, the following function:

def parrot (Voltage, state= ' a stiff ', action= ' voom ', type= ' Norwegian Blue '):
Print ("–this Parrot wouldn ' t", action, end= ')
Print ("If you put", voltage, "volts through it.")
Print ("–lovely plumage, the", type)
Print ("– it ' s", State, "!")
Accepting a required parameter (voltage) and three optional parameters (State,action, and type) can be called with any of the following methods:

Parrot ($) # 1 positional argument
Parrot (voltage=1000) # 1 keyword argument
Parrot (voltage=1000000, action= ' Vooooom ') # 2 keyword arguments
Parrot (action= ' vooooom ', voltage=1000000) # 2 keyword arguments
Parrot (' A million ', ' bereft of life ', ' Jump ') # 3 positional arguments
Parrot (' A Thousand ', state= ' pushing up the Daisies ') # 1 positional, 1 keyword
However, the following types of calls are not valid:

Parrot () # required argument missing
Parrot (voltage=5.0, ' dead ') # Non-keyword argument after a keyword argument
Parrot (voltage=220) # Duplicate value for the same argument
Parrot (actor= ' John Cleese ') # unknown keyword argument
Typically, the parameter list must first write the positional parameter and then the keyword argument, where the keyword must come from the formal parameter. Whether a formal parameter has a default value is not important. No parameter can be assigned multiple times-in the same call, the parameter name that is the same as the positional argument cannot be used as a keyword. Here is an example of an error that violates this limitation:

def function (a):
... pass
...
function (0, a=0)
Traceback (most recent):
File "", Line 1, in?
Typeerror:function () got multiple values for keyword argument ' a '
When a parameter such as **name is introduced, it receives a dictionary that contains all the keyword parameters that do not appear in the formal parameter list. There may also be a combination of form parameters such as *name (described in the next section), which receives a tuple (described in detail in the next sections) and contains all parameter values that are not present in the formal parameter list (*name must appear before **name) For example, we define a function like this

def cheeseshop (Kind, *arguments, **keywords):
Print ("–do You", kind, "?")
Print ("–i ' m Sorry, we ' re all out of", kind)
For ARG in arguments:
Print (ARG)
Print ("-" * 40)
Keys = sorted (Keywords.keys ())
For KW in keys:
Print (KW, ":", keywords[kw])
It can be called like this:

Cheeseshop ("Limburger", "It ' s very runny, sir.",
"It ' s really very, very runny, sir.",
shopkeeper= "Michael Palin",
client= "John Cleese",
Sketch= "Cheese Shop Sketch")
Of course it will print as follows:

–do are there 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
Note the sort () method is called before the contents of the keyword parameter dictionary are printed. Otherwise, the order in which the parameters are printed is undefined.

Variable parameter list

Finally, one of the least common choices is to have the function call a variable number of arguments. These parameters are packed into a tuple (see tuples and sequences). Before these variable number of parameters, there can be 0 to more common parameters.

def write_multiple_items (file, separator, *args):
File.write (Separator.join (args))
Typically, these mutable parameters are the last in the argument list, because they pass all the remaining input parameters to the function. Any arguments that appear after *args are keyword parameters, which means that they can only be used as keywords, not positional parameters.

def concat (*args, sep= "/"):
... return Sep.join (args)
...
Concat ("Earth", "Mars", "Venus")
' Earth/mars/venus '
Concat ("Earth", "Mars", "Venus", sep= ".")
' Earth.mars.venus '
Splitting of parameter lists

In the opposite case: when the argument you are passing is already a list, the function to be called accepts the parameter values separately. At this point you have to take the existing list apart. For example, the built-in function range () needs to be independent of the start, stop parameter. You can automatically take the parameter list apart by adding a * operator when calling the function:

List (range (3, 6)) # Normal call with separate arguments
[3, 4, 5]
args = [3, 6]
List (range (*args)) # Call with arguments unpacked from a list
[3, 4, 5]
In the same way, you can use the * * operator to split the keyword argument into a dictionary:

def parrot (Voltage, state= ' a stiff ', action= ' Voom '):
... print ("–this Parrot wouldn ' t", action, end= ')
... print ("If you put", voltage, "volts through it.", end= ")
... print ("E ' s", State, "!")
...
D = {"Voltage": "Four Million", "state": "Bleedin ' demised", "Action": "Voom"}
Parrot (**d)
–this Parrot wouldn ' t voom if you put a four million volts through it. E ' s bleedin ' demised!
Lambda form

For practical purposes, there are several features commonly found in functional programming languages such as Lisp that have been added to Python. With the Lambda keyword, you can create short, anonymous functions. Here is a function that returns the and of its two parameters: Lambda A, b:a+b. The Lambda form can be used for any function object that is required. They can only have a single expression for syntax restrictions. Semantically, they are only a grammatical technique in the definition of common functions. Similar to nested function definitions, lambda forms can reference variables from outside scopes:

def make_incrementor (n):
... return lambda x:x + N
...
f = make_incrementor (42)
F (0)
42
F (1)
43
The example above uses a lambda expression to return a function. Another use is to pass a small function as a parameter:

pairs = [(1, ' One '), (2, ' One '), (3, ' three '), (4, ' four ')]
Pairs.sort (Key=lambda pair:pair[1])
Pairs
[(4, ' Four '), (1, ' One '), (3, ' three '), (2, ' both ')]
Document string

The concept and format of the document string are described here.

The first line should be an introduction to the object's purpose. For brevity, do not explicitly state object names or types, as they can be learned in other ways (unless the name happens to be a verb that describes the operation of the function). This line should start with a capital letter and end with a period.

If the document string has more than one line, the second line should be empty and clearly separated from the following detailed description. The next document should have one or more paragraphs describing the object's calling conventions, boundary effects, and so on.

The Python interpreter does not remove indents from multiple lines of document strings, so you should clear the indentation yourself when necessary. This is in line with the usual habit. The first non-empty row after the first line determines the indentation format for the entire document. (We don't use the first line because it's usually close to the starting quote, and the indentation format is unclear.) White "equivalent" is the starting indent of the string. Each line should not have indentation, if there is indentation, all the white should be cleared away. The length of the remaining white should be equal to the width of the Extended tab (usually 8 spaces).

The following is an example of a multi-line document string:

Def my_function ():
... "" does nothing, but document it.
...
... No, really, it doesn ' t do anything.
... “””
... pass
...
Print (my_function. Doc)
Do nothing, but document it.

No, really, it doesn‘t do anything.

function comment

function annotations are completely optional, arbitrary metadata information for user-defined functions. Whether it is python itself or using standard library function annotations in any way, this section shows only the syntax. Third party items are free to use feature Notes document type checking and other uses
Note the Annotations property dictionary stored in the function does not affect part of the other functionality. A parameter comment is an expression that is preceded by a colon parameter name followed by the value of a comment. Text-> Returns the comment definition, followed by an expression, which represents the end of the DEF statement between the argument list and the colon. The following example has a positional parameter, a keyword argument, a return value comment, and nonsense:

def f (ham:str, eggs:str = ' eggs ') str:
... print ("Annotations:", F.Annotations)
... print ("Arguments:", ham, eggs)
... return ham + ' and ' + eggs
...
F (' spam ')
Annotations: {' Ham ':

Python Learning (3)-Deep Process Control

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.