Summarize the knowledge points of control flow statements and Python knowledge points in python.

Source: Internet
Author: User

Summarize the knowledge points of control flow statements and Python knowledge points in python.

Program Flow

At the simplest level, the Python interpreter operates in a similar way, starting from the top of the program, and then executes program statements in a row-by-row order. For example, listing 1 shows several simple statements. When you type them in the Python interpreter (or save them in a file and execute them as a Python Program), the order of read statements is from left to right. When a line terminator (such as a line break) is read, the Python interpreter moves forward to the next line and continues until there is no code line.
Listing 1. A simple Python Program

>>> i = 1>>> type(i)<type 'int'>>>> l = [0, 1, 2, 3, 4]>>> l * i[0, 1, 2, 3, 4]

In this example, the statement is followed by a simple order. However, the situation is not always linear. Consider individual examples. You woke up this morning and listened to the traffic or weather report (or both ). Depending on the traffic report, you may have selected a different route to work. Or, similarly, depending on the weather report, you plan different activities for the weekend. Your countermeasures are not simple; according to the information you get, the natural order of life is twists and turns.

Like most programming languages, Python can also be operated in this way by using flow control statements. In Python, there are three basic flow control statements:

  1. If statement, which executes a specific statement block based on the results of the test expression.
  2. While loop, which executes a statement block when a test expression is true.
  3. For loop, which runs a certain number of times on a statement block.

This list is quite simple, and you may know these flow control statements from other programming languages. However, you may wonder what the statement block means. In listing 1, you can see several simple statements, including a variable initialization, a method call (type method), and a multiplication operation. These statements perform a simple operation, so they are called simple statements.

Python also has a composite statement, that is, a group of statements formed by related statements, including simple and (possibly) appended complex statements. For example, based on the expression value (for an individual, it may be the answer to a question like "is today's weather clear ), A compound statement may execute different operations or repeat an operation multiple times. This description seems to be similar to the flow control description in the previous section. Of course it should be similar, because the flow control statement is a composite statement.

A composite statement includes a flow control command followed by a colon (:), followed by a program statement block. A statement block consists of one or more simple statements and compound statements. Listing 2 provides a simple pseudo-code example.
Listing 2. a pseudo-code example shows simple statements and complex statements.

simple statement onecompound statement one:  simple statement two  simple statement three  compound statement two:    simple statement foursimple statement five

The syntax looks familiar and unfamiliar, and the two feelings come from the same thing: indentation. In the column outline or step, you may use different levels of indentation to separate each item, so that the listed items are clearer and more readable. Python follows this model and uses indentation to separate the code block from the rest of the program. Other programming languages use special characters to distinguish code blocks, such as curly braces ({And}) in C-based languages }). These other languages also encourage programmers to use indentation to improve program readability.

On the other hand, Python needs to indent to indicate the code block. If the indentation is not correct, the Python interpreter throws an exception. Tabs can be used to mark indentation, but spaces are generally recommended. (For consistency, I always use four spaces to indent the code block .) The reason is simple: there is only one way to interpret space characters. On the other hand, tabs can be interpreted as two, four, six, or even eight spaces based on the platform or tool used.
Enhance program readability

Indentation requirements may be the best example of a basic guiding principle for Python-the Python program should be easy to read and understand. But like tools, stubborn elements may also write obscure Python code. For example, a screwdriver is used to screw up, but sometimes you may also use it to open the paint lid.

Two other features help write easy-to-read Python programs, both of which follow the analogy of the previous book. First, the rows in the book do not extend to the outside of the page, and they all have a fixed length. Second, the rows in the book do not end with special symbols (such as semicolons. These two features run through the Python programming process.

If a program line is too long, you can continue this line in the next physical line of the file. There is no hard rule on how long a code line should be. However, it is generally limited to 80 characters, which is suitable for a printing page on most monitors. There are several ways to expand code statements that exceed one line:

  • A three-byte string can be extended to multiple rows.
  • The expressions in parentheses can be expanded to multiple rows.
  • You can use the continuous character (\) to separate statements in multiple rows.

In Python, special characters (or symbols) are not required to indicate the end of a statement. This is different from some languages. For example, a semicolon (;) is used to indicate the end of a code line in a C-based language. However, sometimes you need to put multiple program statements in a row, such as when initializing a variable. In this case, you can use a semicolon to separate a single statement.

The two technologies are demonstrated in listing 3.
Listing 3. Demonstrate the readability Technology of Python

>>> i1 = 10 ; i2 = 20 ; i3 = 30>>>>>> b = ((i1 < 20) and...   (i2 < 30) and...   (i3 < 40))>>> bTrue>>>>>> b = (i1 < 20) and \...   (i2 < 30) and \...   (i3 < 40)>>> >>> bTrue

Note how Program Statements expanded to multiple rows in listing 3 are indented to improve readability. In this example, indentation is not mandatory, just like a composite statement. But as you can see, indentation improves the appearance of the program, so it is strongly recommended to indent.

If statement

The simplest flow control statement is the if statement. Its basic syntax is demonstrated in the pseudocode in Listing 4. If statement executes a Program Statement block when a Boolean expression is calculated as True. The if Statement supports an optional else clause, indicating the Program Statement block to be processed when the Boolean expression is calculated as False.
Listing 4. Basic syntax of the if statement

if(expression one):  # Action to take if expression one evaluates Trueelse:  # Action to take if all expression one evaluates False

If you have used other programming languages, the syntax may seem familiar and unfamiliar. The similarity lies in the general format and name of the if statement, the formula used to determine how the stream is executed in the branch statement, and the else clause used to process the case where the expression is calculated as False. But there are two aspects that are completely specific to Python: the termination of the if and else statements with colons, And the indentation of the statements in the if and else blocks. As mentioned, these two features are required by the Python flow control statement.

In listing 5, a simple if/else condition tests whether a given number is an odd or even number and prints the result.
Listing 5. A simple if statement example

>>> i = 8>>> if(i % 2):...   print "Odd Number"... else:...   print "Even Number"... Even Number

The first three vertices (...) in each line after the if statement (...). When you type the if statement and the ending colon and press the Enter key on the drive, the Python interpreter knows that you have entered a compound statement. Therefore, it changes the prompt from three vertices (>) to three vertices (...). Because Python needs to indent the statement block that should be executed when the expression is calculated as True or False, four spaces are indented for both print statements.

The expressions in the if Statement (and the elif clause and while LOOP discussed later in this article) can be complex. It can contain multiple subexpressions that use different Relational operators supported in Python. The sub-expressions can be combined using the and, or, and not logical operators. The first article in this series, "explore Python, Part 1: Python's built-in numeric type", contains

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.