[Python] program structure and control flow

Source: Internet
Author: User
Tags assert

1. Conditional statements

The IF, else, and elif statements are used to control the execution of conditional code. The general format of the conditional statement is as follows:

if expression:    statementselif expression:    statementselif expression:    statements...else:    statements

If you do not need to perform any action, you can omit the else and elif clauses of the conditional statement. If the statement to execute does not exist under a specific clause, you can use the PASS statement.

2. Loops and Iterations

Loops can be implemented using the for and while statements, for example:

while expression:    statementsfor i in s:    statements

The While statement executes the statement in the loop body repeatedly. Until the correlation expression evaluates to False. The For statement iterates through all the elements in S, until the element is available again. The For statement applies only to objects that can support iterations.
If the element used in the iteration is a sequence of exactly the same size as the element, each iteration of the sequence assigns the elements of the corresponding series to the variables x, y, and Z. Although S is mostly a tuple sequence when using this line of code, items in s can be any sequence of types, including lists, generators, and strings.
When looping, in addition to the data values, there are times when you need to track a numeric index, you can use the built-in function enumerate (), for example:

for i,x in enumerate(s):    statements

Enumerate (s) creates an iterator whose return value is a sequence of tuples (0, s[0]), (1, s[1]), (2, s[2]), and so on. Another common problem with iterations is that more than two sequences are iterated in parallel, and you can use the zip () function, for example:

for x, y in zip(s, t):    statements

Zip (S, t) combines the sequence s and t into a tuple sequence (s[0], t[0]), (S[1], t[1]), (s[2], t[2]), and so on. If the length of s and T are not equal, the index of the shortest length is exhausted.
Use the break statement to jump out of a loop, for example:

for line in open("foo.txt"):    stripped = line.strip()    if not stripped:        break # 遇到空行,停止读取

Use the continue statement to jump to the next iteration of the loop, for example:

for line in open("foo.txt"):    stripped = line.strip()    if not stripped:        continue # 跳过空行
3. Exceptions

Exceptions interrupt the normal control flow of the program. Use the Raise statement to throw an exception. The general format of the raise statement is raise Exception ([value]), where Exception is the exception type, and value is an optional value that specifies the details of the exception, such as:

raise RuntimeError("unrecoverable Error")

If the raise statement does not take any arguments, the last generated exception is raised again. Use the try and except statements to catch exceptions, such as:

try:    f = open(‘foo‘)except IOError as e:    statements

When an exception occurs, the interpreter stops executing the statement in the try code block and looks for an except clause that matches the exception. After the EXCEPT clause is executed, control is passed to the first statement that appears after the Try-except code block. Try-except statements can be used in a nested set. If the exception is passed to the top of the program and is still not captured, the interpreter terminates the program run.
Optional modifier for except statement as VAR provides a variable name in which an instance of the exception type provided to the raise statement is placed if an exception occurs. The exception handler can check the value, or you can use the Isinstance () function to check the exception type.
Handlers can catch many types of exceptions, and using exception can catch all exceptions except those related to program exits, such as:

try:    do somethingexcept (IOError, TypeError) as e:    # 处理I/O、类型异常except Exception as e:    # 处理所有异常

All exceptions are also caught when using the except statement without any exception type, for example:

try:    do somethingexcept:    # 处理所有异常

The Try statement also supports the ELSE clause, which must be followed by the last except clause. If the code in the try code block does not throw an exception, the code in the ELSE clause is executed, for example:

try:    f = open(‘foo‘, ‘r‘)except IOError as e:    # 处理I/O异常else:    data = f.read()    f.close()

The finally statement defines the end operation for the code in the try code block, for example:

f = open(‘foo‘, ‘r‘)try:    # do somethingfinally:    f.close()

Finally is used to provide some code that must be executed, whether or not an error occurs. If no exception is thrown, the code in the finally clause executes immediately after the code in the try code block has finished executing. If an exception is thrown, control is first passed to the first statement of the finally clause. Once this code is executed, it is referred to another exception handler for processing.
If you want to create a new exception, define a new class for which the parent class is exception, for example:

class NetworkError(Exception):    pass

You can use this exception in the following ways:

raise NetworkError("Cannot find host.")

When an exception is thrown, the optional value that is supplied to the raise statement is used as an argument to the class constructor of the exception. Typically, it is a string that represents a message, but a user-defined exception can have one or more outliers, such as:

class DeviceError(Exception):    def __init__(self,errno,msg):        self.args = (errno,msg)        self.errno = errno        self.errmsg = msgraise DeviceError(1, ‘Not Responding‘)

The tuple that contains the __init__ () method parameter is assigned to the attribute Self.args. This property is required to print the exception trace message. If you do not define this property, the user cannot see useful information about the exception when an error occurs.

4. Context management and with statements

The WITH statement supports the execution of a series of statements in the run-time context controlled by the context Manager object, for example:

with open("debuglog", "a") as f:    f.write("Debugging\n")    statements    f.write("Done\n")import threadinglock = threading.Lock()with lock:    statements

In the first small piece of code, when the control flow leaves the code block following the WITH statement, the WITH statement automatically closes the open file. In the second piece of code, a lock is automatically requested when the control flow enters the code block following the WITH statement, and the lock is automatically freed when the control flow leaves.
The WITH OBJ statement allows the object obj to manage what happens when the control flow enters and leaves the relevant block of code behind it. When executing a with OBJ statement, it executes method obj.__enter__ () to indicate that a new context is entering. When the control flow leaves the context, the method obj.__exit__ (type, value, Traceback) is executed. If no exception is thrown, the 3 parameters of the __exit__ () method are set to none. Otherwise, they will contain the type, value, and trace information associated with the exception that caused the control flow to leave the context. The __exit__ () method returns True or false, indicating whether the exception being thrown has been or is not being processed.
The WITH OBJ statement accepts an optional as Var specifier, and if specified, the return value of the obj.__enter__ () method is saved in Var. The WITH statement is valid only for objects that support the context Management Protocol (__ENTER__ () and __exit__ () methods). User-defined classes can implement these methods to define their own custom context management. For example:

class ListTransaction(object):    def __init__(self, thelist):        self.thelist = thelist    def __enter__(self):        self.workingcopy = list(self.thelist)        return self.workingcopy    def __exit__(self, type, value, tb):        if type is None:            self.thelist[:] = self.workingcopy        return False
5. Assertions and Debug

An Assert statement can introduce debugging code into a program. The general format of the Assert is:

    assert test [, msg]

Where test is an expression whose value should be true or false. If test evaluates to False,assert, the Assertionerror exception is thrown and the optional message msg provided in the Assert is used, for example:

    def write_date(file, data):        assert file, "write_data: file not defined"

In addition to the Assert statement, Python provides a built-in read-only variable, __debug__, unless the interpreter is running in optimal mode, and its value is true. The program can check this variable as needed.

[Python] program structure and control flow

Related Article

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.