Summarizing the knowledge points of the control flow statements in Python _python

Source: Internet
Author: User
Tags logical operators readable switch case in python

Program Flow

At its simplest level, the Python interpreter operates in a similar manner, starting at the top of the program, and then executing the program statement sequentially, line by line. For example, listing 1 shows a few simple statements. When you type them into the Python interpreter (or save them in a file and execute as a Python program), the order of the read statements is left to right. When you read a line terminator (such as a newline character), the Python interpreter advances to the next line and continues until there is no line of code.
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 case, the statements are one after the other in a simple order. But the situation is not always linear. Consider a personal example. You woke up this morning and listened to traffic or weather reports (or both). Depending on the traffic report, you may have chosen a different route to work, or similarly, depending on the weather report, you have planned different activities for the weekend. Your response is not simple; According to the information you get, the natural order of life twists and turns.

Python, like most programming languages, can operate in this way by using flow control statements. In Python, there are 3 basic types of flow control statements:

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

This list is fairly simple, and you may know these flow control statements from other programming languages. But you may be wondering what the statement block means. In Listing 1, you see several simple statements, including a variable initialization, a method call (the type method), and a multiplication operation. These statements perform a simple operation, so they are referred to as simple statements.

Python also has a compound statement, a group of statements formed by related statements, which includes simple and (possibly) additional complex statements. For example, depending on the value of the expression (for an individual, perhaps the answer to "today's fine Weather"), a compound statement might perform a different operation or repeat several times for an operation. This description seems to be somewhat analogous to the flow control described in the previous paragraph. It should be similar, of course, because flow control statements are compound statements.

A compound statement consists of a flow control instruction followed by a colon (:) and then a block of program statements. A statement block consists of one or more simple statements and compound statements. A simple pseudo code example is provided in Listing 2.
Listing 2. A pseudo code example shows simple statements and complex statements

Simple statement one
compound statement one: Simple
  statement Two simple
  three Statement two: Simple
    statement Four simple
statement five

The syntax looks familiar and unfamiliar, and the two sensations come from the same thing: indentation. When you column an outline or step, you might use different levels of indentation to separate each item, making the items listed more readable. Python follows this model, using indenting to separate blocks of code from the rest of the program. Other programming languages use special characters to differentiate blocks of code, such as curly braces ({and}) in a C-based language. These other languages also encourage programmers to use indents to improve the readability of programs.

Python, on the other hand, needs to indent to indicate a block of code. The Python interpreter throws an exception if it is not indented correctly. You can use tabs to mark indents, but it is generally recommended that you use spaces. (for consistency, I always use 4 spaces to indent blocks of code.) The reason is simple: there is only one way to interpret a space character. On the other hand, tabs can be interpreted in different ways, depending on the platform or tool used, which can be interpreted as 2, 4, 6, or even 8 spaces.
Enhance program readability

Indentation requirements may be the best example of Python's basic guiding principles--python programs should be easy to read and understand. But as with tools, stubborn molecules may write obscure Python code. For example, a screwdriver is used to screw up, but sometimes you may also be able to open the paint lid.

Two other features help you write readable Python programs, both of which follow the metaphor of the previous book. First of all, the lines in the book do not extend to the outside of the page, there is a fixed length. Second, the lines in the book Do not end with special symbols (such as semicolons). Both of these features are throughout the process of writing a Python program.

If a program line is too long, you can continue this line in the next physical row in the file. There is no hard rule about how long a line of code should be. But the general limit is 80 characters, which is easy for a printed page on most monitors. There are several ways to extend a code statement that is more than one line:

    • Three-quote strings can be extended to multiple rows.
    • The expressions in parentheses can be extended to multiple rows.
    • You can use the continuation character (\) to split a statement across multiple lines.

In Python, you do not need to use special characters (or symbols) to indicate the end of a statement. This is different from some languages. For example, a language based on C uses a semicolon (;) to indicate the end of a line of code. However, there are times when you need to place multiple program statements on a single line, such as initializing variables. In such cases, you can use semicolons to separate individual statements.

The two techniques are shown in Listing 3.
Listing 3. Demo Python's Readability technology

>>> i1 = 10; I2 = 20; i3 =
>>> b = (I1 <) and
...   (I2 <) and
...   (i3 <))
>>> b
>>> b = (I1 <) and \
...   (I2 <) and \
...   (i3 <)
>>> b

Note how the program statements that are extended to multiple rows in Listing 3 are indented to improve readability. In this case, indentation is not mandatory, just like a compound statement. But as you can see, indenting improves the appearance of the program, so it's highly recommended for indentation.

If statement

The simplest flow control statement is the IF statement, and its basic syntax is demonstrated in the pseudo code in Listing 4. The IF statement executes a block of program statements when a Boolean expression evaluates to True. The IF statement supports an optional ELSE clause that indicates the block of program statements that should be processed when the Boolean expression evaluates to False.
Listing 4. The basic syntax of an IF statement

if (expression one):
  # Action to take if expression one evaluates True
  # action to take if all express Ion one evaluates False

If you have used other programming languages, the syntax may look familiar and unfamiliar. The similarity lies in the general format, name of the IF statement, the calculation of the expression that determines how the flow is executed by the spoke statement, and the ELSE clause that is used to handle the case when the expression evaluates to False. But there are two aspects that are completely Python-specific: The termination of IF and else statements with colon characters, and the indentation of statements in if and else blocks. As mentioned, these two features are required by the Python mid-stream control statement.

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

>>> i = 8
>>> if (i% 2):
...   Print "ODD number"
... else:
...   Print "Even number"
Even number

One place that seems a bit confusing is the three dots (...) before each line in the following if statement. )。 When you type an if statement and a terminated colon, and press ENTER on the keyboard, the Python interpreter knows that you have entered a compound statement. As a result, it changes the prompt from three greater than symbol (>>>) to three dots (...). )。 Because Python requires indentation to stagger the block of statements that should be executed when the expression evaluates to True or False, two print statements indent 4 spaces.

An expression in an if statement (and the ELIF clause and the while loop discussed later in this article) can be complex. It can include multiple subexpression expressions that use different relational operators that are supported in Python. The subexpression can also be combined with and, OR and not logical operators. The first article in this series, "Explore Python, part 1th: Python's built-in numeric types", contains more information about the different relationships and logical operators in Boolean expressions and Python.

At this point, you have seen how the IF statement can be used to execute one of the two block of program statements based on the value of a particular Boolean expression. In some cases, however, more options may be required. Fortunately, Python provides a simple extension of the IF statement. The solution provided is simple: add an extra if statement to the ELSE clause. The result is an else if statement, abbreviated as ELIF, as shown in Listing 6.
Listing 6. Using the Elif statement

>>> i =-8
>>> if (i > 0):
...   Print "Positive Integer"
... elif (i < 0):
...   Print "Negative Integer"
... else:
...   Print "Zero"
Negative Integer

This example contains only one elif statement, but in practice you can include as many as you want according to your program. Although it is not the optimal solution, multiple elif statements can be used to simulate switch case statements in other languages.

While loop

The second type of flow control statement in Python is a while loop, which executes a block of program statements when an expression evaluates to True. The while loop, like an if statement, supports an optional ELSE clause that contains a block of program statements that executes when the expression evaluates to False. But for a while loop, this means that after the loop terminates, the code in the ELSE clause is executed once (see the pseudo code in Listing 7).
Listing 7. Pseudo code for While loop

while (expression):
  # statements to execute while loop expression are True
  # statements to execute when l OOP expression is False

After understanding the IF statement, the while loop is fairly straightforward to understand. But it's important to know that the loop always executes to the expression evaluates to False. This means that the program statement executed in the loop body must change the value of the expression, otherwise the loop will not end. As shown in Listing 8.
Listing 8. A simple example of a while loop

>>> i = 0; x =
>>> while (x > 0):
...   I+=1; x = 1
... else: ...   Print I, x ... 
10 0

This example demonstrates a few things. First, it combines variable initialization and variable modification in one row: In this case I and X variables. Second, you increment the value of I and decrement x by using the abbreviated operators + = and-= respectively. In this case, the value of X at the start of the loop is 10. Each time the loop is passed, the value of x decreases by 1. Finally, the value of x is 0, and then the loop exits and executes the code in the ELSE clause to print out the values of the two variables.

The while loop (like the For loop described later in this article) supports three additional statements:

    1. Continue
    2. Break
    3. Pass

The continue and break statements are used to continue the next loop or interrupt loop in the while loop, respectively. These two statements are usually placed in the IF statement body to trigger the continue or break operation by a particular condition. A special feature of a break statement is that it completely interrupts the loop and jumps to any else clause below the loop.

The pass statement does nothing. It is used as a placeholder when a statement is needed, but the program logic does not need to be manipulated. The three statements are shown in Listing 9.
Listing 9. Using continue, break, and pass statements

>>> i = 1
>>> while (i < 1000):
...   I *= 5 ...   if (i%): ...     Continue ...   If not (i%): ...     Break
...   If not (i% 1000):
...     Pass
... else: ...   Print I ... 
>>> Print I

This fictitious example has been circulated to the variable i is greater than or equal to 1,000. In the loop, multiply I by 5, and then test if I is divisible by 25. Remember, you only execute the IF statement body when the expression is True. The expression evaluates to True when the variable I cannot be divisible by 25. (In a Python expression, a zero is evaluated to the Boolean value True.) )

The next statement in the loop body is the second if statement that tests whether the variable I can be divisible by 125, but the expression is preceded by a not operator. Therefore, when the value of the variable I can be divisible by 125, the second if statement body is executed. At this point, the break statement causes the program to execute an interrupt while loop and jump to the ELSE clause.

The last if statement is never executed, but is used to demonstrate how to write a pass statement in a program. In subsequent articles, there will be some more relevant information about the PASS statement.

By tracking the logic flow of the program, you can see that the first time through the loop, the value of the variable I becomes 5. The first if statement evaluates to True because 5 cannot be divisible by 25. This will go into the while loop for the second time, and this time the variable I becomes 25. The first if statement now evaluates to False because 25 can be divisible by 25. The second and third if statements are also evaluated as False, which means that the third time into the loop. This time the variable I becomes 125, and the first if statement evaluates to False.

The second if statement evaluates to true, however, because the variable I can be divisible by 125 (and the NOT operator converts result 0 to a Boolean value of true). This causes the break statement to be executed and interrupts the loop. The ELSE clause will never be executed, so it will not output anything until the print statement is explicitly used.

For loop

The For loop in Python is very special, closely related to the container data type built into the Python programming language. When you have a container object (such as a schoolbag) in real life, you usually want to see what it contains. This is also true when writing a Python program. Use a For loop when you need to do something a certain number of times (just as you would for each item in a container). The pseudo code format in Listing 10 demonstrates a for loop.
Listing 10. Pseudo code for Loop

For item in container:
  # action to repeat for each item in the container
  # action to take once we have F Inished the loop.

Because of the rich nature of the Python container type, the For loop is very powerful. In essence, A For loop involves an iterator (iterator) that is used to move one item at a set. The next article in this series will describe the for loop in more detail and how to properly use it with different container types.

Control flow

This article describes three kinds of Python program statements: If statements, while loops, and for loops. These three statements allow you to change the flow of a program by selecting which statements to execute, or by executing a set of statements multiple times. These statements will be used extensively in subsequent articles. The attributes of compound statements introduce the appropriate indentation features in the Python program, which makes the Python program easy to read and understand.

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: 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.