This article describes in detail three options in Python: If statements, if/else statements, and if/Elif/else statements. For each statement, we provide the corresponding flowchart. At the same time, we provide many simple sample programs to help readers better understand.
I. Program Control Structure
By default, the execution statements in the python program are executed in the order of writing. In this case, the statements are structured in order. However, only sequential structure is not enough, because sometimes we need to selectively execute certain statements based on specific situations. In this case, we need a statement with a structure selected. In addition, sometimes we can execute some statements in a given condition. In this case, we call these statements a loop structure. With these three basic structures, we can build any complicated program.
For this article, we will discuss the selection structure in the three basic program structures, which are implemented using the if statement, if/else statement, and if/Elif/else Statement respectively. The other two control structures will be introduced in subsequent articles. Next we will first introduce the if statement.
II. If statement
The function of the IF statement in python is very similar to that in other languages. It is used to determine whether the given condition is met, and then determines whether to execute the given operation based on the result (true or false. The IF statement is a single-choice structure, which selects "do" or "do not. It is composed of three parts: the keyword if itself, the expression of the true or false test condition (referred to as the condition expression), and the expression result is true (that is, the value of the expression is non-zero) the code to be executed. The syntax of the IF statement is as follows:
If expression:
Statement body
The IF statement flowchart is as follows:
Figure 1 If statement Flow
Note: The if statement body is executed only when the value of the conditional expression is true, that is, the statement body is not zero. Otherwise, the program will directly skip this statement body, execute the statement that follows the body of the statement. Here, the statement body can contain both multiple statements and only one statement. However, when the statement body is composed of multiple statements, it must have a uniform indent form, otherwise, a logical error occurs, that is, the syntax check is correct, but the result is not expected.
Now we use an example program to demonstrate the if statement usage. Our program is very simple, as long as the user inputs an integer, if this number is greater than 6, then output a line of string; otherwise, exit the program directly. The Code is as follows:
#-*-Coding: cp936 -*-
# Compare whether the input integer is greater than 6
Integer = raw_input ('enter an integer: ') # obtain a string
Integer = int (integer) # convert a string to an integer
If integer> 6:
Print '% d greater than 6' % integer
When we run this program in idel, the results are as follows:
Figure 2 If statement sample program running result
We can see that if the entered number is not greater than 6, the program will exit immediately, that is, the following code
Print '% d greater than 6' % integer
Not executed; if the number entered is greater than 6, the above line of code will be executed to print a line of text.
Iii. If/else statements
The above if statement is a single-choice structure. That is to say, if the condition is true (that is, the expression value is non-zero), the specified operation is executed; otherwise, the operation is skipped. Therefore, it chooses whether to do or not. The IF/else statement is a two-choice structure. It does not select whether to do or not, but the question of which to choose between the two alternative actions. The IF/else statement is composed of five parts: If keyword, expression with true or false test conditions, and code to be executed when the expression result is true (that is, the expression value is non-zero, and the code to be executed when the keyword else and expression result are false (that is, the expression value is zero. The syntax of the IF/else statement is as follows:
If expression:
Statement body 1
Else:
Statement Body 2
The process of the IF/else statement is as follows:
Figure 3 if/else statement process
From the process of the IF/else statement, we can easily see that when the condition is true (that is, the expression value is non-zero), the execution statement body 1; when the condition is false (that is, the expression value is zero), the execution statement body 2 -- that is, whether the condition is true or false, it always selects an execution from the two statement bodies, the title of the double-choice structure comes from this.
Next we will modify the preceding example to demonstrate how to use the IF/else statement. Our program is very simple, as long as the user inputs an integer, if this number is greater than 6, then output a line of information, indicating that the input number is greater than 6; otherwise, output another line of string, indicates that the input number is less than or equal to 6. The Code is as follows:
#-*-Coding: cp936 -*-
# Compare whether the input integer is greater than 6
Integer = raw_input ('enter an integer: ') # obtain a string
Integer = int (integer) # convert a string to an integer
If integer> 6:
Print '% d greater than 6' % integer
Else:
Print '% d is smaller than or equal to 6' % integer
When we run this program in idel, the results are as follows:
Figure 4 If/else statement example program running result
When the input number is less than 3, that is, when the condition expression is false, run the print statement in the else statement:
Print '% d is smaller than or equal to 6' % integer
When the input number is less than 3, that is, when the condition expression is false, execute the print statement in the else statement:
Print '% d greater than 6' % integer
However, in any case, it must be executed by one of the two print statements, and neither of them can be skipped.
4. If/Elif/else statements
Sometimes, we need to select a group of execution in multiple groups of actions. In this case, the multi-choice structure is used. For python, It is the IF/Elif/else statement. This statement can use a series of conditional expressions to check and execute the corresponding code when an expression is true. Note that although the IF/Elif/else statements have many alternative actions, only one group of actions is executed. the syntax of this statement is as follows:
If expression 1:
Statement body 1
Elif expression 2:
Statement Body 2
......
Elif expression m:
Statement body m
Else:
Statement body n
Note,The else clause after the last Elif clause does not perform condition judgment. In fact, it does not match all the preceding conditions. Therefore, the conditions processed by the else statement are called the default conditions, therefore, else words must be placed at the end. The IF/Elif/else statement is as follows:
Figure 5 If/Elif/else statements
Next, we will continue to modify the preceding example program to demonstrate how to use the IF/Elif/else statement. We still need to enter an integer. If the number is greater than 6, a line of information is output, indicating that the number entered is greater than 6. If the number is smaller than 6, another line of string is output, indicates that the input number is less than 6; otherwise, it indicates that the input number is equal to 6. The specific code is as follows:
# -*- coding: cp936 -*-
# Compare whether the input integer is greater than 6
Integer = raw_input ('enter an integer: ') # obtain a string
Integer = int (integer) # convert a string to an integer
If integer> 6:
Print '% d greater than 6' % integer
Elif integer <6:
Print '% d less than 6' % integer
Else:
Print '% d equals 6' % integer
When we run this program in idel, the results are as follows:
Figure 6 if/Elif/else statement example program running result
The above describes the basic usage of the three selection statements. Next we will introduce the combination of these selection structures, as well as the precautions for using the selection statements, including notes for indentation and expressions.
5. Combination of selected Structures
In general, there are two basic structures in structured programming: sequential structure, selection structure, and cyclic structure. One is stack mode, and the other is nested mode. The stacking method is simple. It lists all the structures one by one. For example, we can stack the if statement in a selected structure with the sequence structure, as shown below:
Figure 7 stack of Ordered Structure and selected Structure
We can see that because the three basic structures are single-entry and single-exit (usually expressed in a small circle), you only need to connect the exit of one structure to the entrance of another structure when stacking. As for the nested combination method, it is to replace the statement body in the same structure with a structure (we usually use a rectangle box ), indicates nesting the if statement in one selection structure into another if statement:
Figure 8 If statement nesting
It is not difficult to find that the nested above is actually replacing the statement body (rectangular box) in an if structure with another if structure. The nesting of other structures is similar to this. Here we will not list them one by one.
Here is an example to illustrate nested applications. We need to compare the number entered by the user with an integer and output the comparison result. This can be done with the IF/Elif/else statement, but to demonstrate the nesting of the selection structure, we use the nested if/else statement here. The Code is as follows:
# -*- coding: cp936 -*-
# Compare the entered number with 6
Integer = raw_input ('enter an integer: ') # obtain a string
Integer = int (integer) # convert a string to an integer
If integer> 6:
Print '% d greater than 6' % integer
Else:
If integer <6:
Print '% d less than 6' % integer
Else:
Print '% d equals 6' % integer
When we run this program in idel, the results are as follows:
Figure 9 If/else nested statement example program running result
Vi. Statement body indentation
It should be noted that the indentation must be paid attention to during nesting. The C language uses braces {} to differentiate the statement bodies, but the python statement bodies are represented in indentation. If the indentation is incorrect, a logical error will occur. For example, if we ask the user to enter a number, if the number is an even number, the information of the two rows is printed. One row indicates that the number is divided by the remainder of 2, and the other row indicates the judgment result. The Code is as follows:
# -*- coding: cp936 -*-
# Determine whether the input number is an even number
Integer = raw_input ('enter an integer: ') # obtain a string
Integer = int (integer) # convert a string to an integer
If 0 = integer % 2:
Print '\ n % d divided by the remainder of 2 to zero;' % integer
Print ', % d is an even number' % integer
When we run this program in idel, the results are as follows:
Figure 10 result of correct indent
If we change the indent of the second print statement of the IF statement in the above program, for example,:
If 0 = integer % 2:
Print '\ n % d divided by the remainder of 2 to zero;' % integer
Print ', % d is an even number' % integer
Let's take a look at the running results:
Figure 11 incorrect indentation results in logical errors
, There is an obvious logical error. Because python uses indentation to differentiate the boundary of the statement body, when the second print statement in the example is not indented, it is out of the control range of the IF statement, therefore, the IF statement is executed no matter whether the condition of the IF statement is true.
7. Select the conditional expression in the statement
Now, we need to introduce the conditional expressions in the selection statement. Among the three selection statements, the conditional expressions are all essential components. If the value of a conditional expression is zero, the condition is false. If the value of a conditional expression is non-zero, the condition is true. Which expressions can be used as conditional expressions? Basically, relational expressions and logical expressions are commonly used, such:
If a = x and B = Y:
Print 'a = X, B = y'
In addition, the conditional expression can be any numeric type expression, or even the numeric type:
Figure 12 use a character as a condition expression
VIII. Summary
This article describes in detail three selection statements in Python. When we first come into contact with these selection structures, we 'd better draw more flowcharts, which is very helpful for understanding the logic of the program. In addition, the hands-on practice is also essential. The sample programs in this article are all demonstrated in the idel environment. How to Use idel is as follows, you can refer to the previous article "step-by-step Python idle learning.