Summarize the knowledge points of control flow statements in Python

Source: Internet
Author: User
Tags switch case
Program Flow

The Python interpreter operates in a similar manner at its simplest level, starting at the top of the program and then executing the program statements in a row and line. For example, listing 1 shows a few simple statements. When they are typed into the Python interpreter (or saved in a file and executed as a Python program), the order in which they are read is left-to-right. When a line terminator (such as a newline character) is read, 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)
 
  
   
  >>> L = [0, 1, 2, 3, 4]>>> L * i[0, 1, 2, 3, 4]
 
  

In this example, the statements are one after the other in a simple order. But the situation is not always linear. Consider an example of an individual. 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 of 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 also operate in this way by using flow control statements. In Python, there are 3 basic flow control statements:

    1. If statement, which executes a specific block of statements based on the results of the 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 block of statements.

This list is fairly straightforward, and you may be aware of these flow control statements from other programming languages. But you might be thinking, what does a statement block mean? In Listing 1, you see a few simple statements, including a variable initialization, a method invocation (type method), and a multiplication operation. These statements perform a simple operation, so they are called simple statements.

Python also has compound statements, which are groups of statements formed by related statements, including simple and (possibly) additional complex statements. For example, depending on the value of an expression (for an individual, it might be the answer to a question like "Today's Sunny Day"), a compound statement might perform different actions or repeat multiple times for an operation. This description seems somewhat similar to the flow control description in the previous paragraph. It should, of course, be similar, 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 a simple statement and a complex statement

Simple statement Onecompound Statement one: simple statement, simple statement three compound statement  The other: Simple    statement foursimple statement Five

The syntax looks familiar and unfamiliar, and the two senses come from the same thing: indentation. When you column an outline or step, you may use different levels of indentation to separate each item, making the list clearer and more readable. Python follows this model by using indentation 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 C-based languages. These other languages also encourage programmers to use indentation to improve the readability of the program.

On the other hand, Python needs to be indented to indicate a block of code. If it is not indented correctly, the Python interpreter throws an exception. You can use tabs to mark indents, but it is generally recommended to use spaces. (for consistency, I always use 4 spaces to indent blocks of code.) The reason is simple: the space character has only one way to interpret it. On the other hand, tabs can be interpreted in different ways, depending on the platform or tool used, and 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 guidelines--python programs should be easy to read and understand. But as with tools, stubborn molecules can also write obscure Python code. For example, a screwdriver is used to screw, but sometimes you may also use it to open the paint lid.

Two other features help to write easy-to-read Python programs, and both follow the analogy of the book used earlier. First, the lines in the book do not extend to the outside of the page and have a fixed length. Second, the lines in the book Do not end with special symbols (such as semicolons). Both of these features are used throughout the process of writing a Python program.

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

    • A three-quote string can be extended to multiple lines.
    • Expressions in parentheses can be extended to multiple rows.
    • You can use the continuation character (\) to split the statement in 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 C-based language uses a semicolon (;) to indicate the end of a line of code. However, there are times when you need to put more than one program statement on a line, such as initializing a variable. In such cases, you can use semicolons to separate individual statements.

The two techniques are demonstrated in Listing 3.
Listing 3. Demonstrating the readability techniques of Python

>>> i1 = 10; I2 = 20; i3 = 30>>>>>> B = ((I1 <) and ...   (I2 <)   and ... (i3 < 40)) >>> btrue>>>>>> B = (I1 <) and \ ...   (I2 <) and \ ...   (i3 < +) >>> >>> btrue

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

If statement

The simplest flow control statement is an 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 handled when the Boolean expression evaluates to False.
Listing 4. Basic syntax for an 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 is in the general format of the IF statement, the name, the evaluation of an expression that determines how the branch statement executes the flow, and the ELSE clause that handles the case when the expression evaluates to False. However, there are two aspects that are completely Python-specific: The termination of the IF and else statements with the colon character, and the indentation of the statements in the IF and else blocks. As mentioned, these two characteristics are required by the Python stream control statement.

In Listing 5, a simple if/else condition tests whether a given number is odd or even, and prints 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

A somewhat confusing place is the three dots (...) preceding each line of the IF statement. )。 When you type the IF statement and the terminating colon, and press the ENTER key on the keyboard, the Python interpreter knows that you have entered a compound statement. As a result, it changes the prompt from three to three points (>>>) to a point (...). )。 Because Python needs to indent to stagger the block of statements that should be executed when the expression evaluates to True or False, the two print statements are indented 4 spaces.

Expressions in the If statement (and the ELIF clause and the while loop discussed later in this article) can be complex. It can include multiple sub-expressions that use different relational operators that are supported in Python. Sub-expressions can be combined with and, or, and not logical operators. The first article in this series, "Explore Python, part 1th: Python's built-in numeric type," contains more information about Boolean expressions and different relationships and logical operators in Python.

At this point, you have seen how the IF statement can be used to execute one of the two program statement blocks based on the value of a particular Boolean expression. In some cases, however, more choices may be needed. Fortunately, Python provides a simple extension of the IF statement. The solution provided is very simple: add an additional 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, and can actually contain as many as you want in the program. Although it is not an optimal solution, multiple elif statements can be used to emulate switch case statements in some other languages.

While loop

The second 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 the IF statement, supports an optional ELSE clause that contains a block of program statements that executes when the expression evaluates to False. But for the while loop, this means that the code in the ELSE clause is executed once after the loop terminates (see pseudocode in Listing 7).
Listing 7. Pseudo-code for While loop

while (expression):  # Statements-execute while loop expression was trueelse:  # statements to execute when Loop E Xpression is False

After understanding the IF statement, the while loop is quite simple to understand. But be sure to know that the loop is always executed until the expression evaluates to False. This means that the program statement executed in the loop body must change the value of the expression or the loop will not end. This is shown in Listing 8.
Listing 8. A simple example of a while loop

>>> i = 0; x = 10>>> 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. Next, use the abbreviated operator + = and-= to increment the value of I and decrement the value of X. In this example, the value of X at the start of the loop is 10. Each time a loop is passed, the value of X is decremented by 1. Finally, the value of x is 0, at which time the loop exits and executes the code in the ELSE clause, printing 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 so that the continue or break operation is triggered by a special condition. A special feature of the 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, that is, when a statement is required, but the program logic does not need to be manipulated. The three types of statements are shown in Listing 9.
Listing 9. Using continue, break, and pass statements

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

This fictitious example has been circulating to the variable i is greater than or equal to 1,000. In the loop, multiply I by 5, and then test whether I is divisible by 25. Remember that 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 Python expressions, non-zero is evaluated as a Boolean value of True.) )

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

The last if statement is never executed, just to demonstrate how to write a pass statement in a program. In a subsequent article, you'll describe some of the more relevant scenarios for pass statements.

By tracing the logical flow of the program, you can see that the value of the variable I changes to 5 after the first pass through the loop. 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 variable I becomes 25. Now the first if statement 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 entry is in a loop. This time the variable I becomes 125, and the first if statement evaluates to False.

But the second if statement evaluates to TRUE because the variable I can be divisible by 125 (and the NOT operator converts the result 0 to a Boolean value of true). This causes the break statement to be executed, which interrupts the loop. The ELSE clause is never executed, so nothing is output until you explicitly use the print statement.

For loop

The For loop in Python is special and closely related to the container data types 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 true when you write a Python program. Use a For loop when you need to do something for a certain number of times (as you would for each item in the container). The pseudo-code format in Listing 10 demonstrates the for loop.
Listing 10. Pseudo-code for the For loop

For item in container:  # action to repeat for each item in the Containerelse:  # Action to take once we have finish Ed the loop.

Because of the rich nature of the Python container type, the For loop is very powerful. Essentially, a For loop involves an iterator (iterator) that moves one item at a collection. The next article in this series describes the for loop in more detail, and how to properly use it with different container types.

Control flow

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

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