Column address: The strongest Python 3 Foundation
Official account: Python productivity
preface
Programming, in fact, is to express what we think in our hearts in code, so that the program can execute the code we write according to the established process and obtain the corresponding results.
In the process of program execution, some conditional judgment cannot be avoided. Just like us humans, we will make decisions when there are differences in something. The program written at this time also needs to make certain decision judgment under corresponding conditions. This is the conditional control in the program.1, if conditional control
Condition control: when one or more conditions occur, different code blocks are executed according to the judgment of the conditions to achieve the corresponding results. We can see the condition control in the standard program according to the following simple flow chart.
From the figure, we can see that a condition control can be mainly divided into three parts: condition, executed program and final result.
In fact, the judgment of conditions in Python is based on the if keyword, that is, if you need to judge at a certain step, you need to add this if. The whole code process is an execution process of if - executing program - or - executing program - other cases - executing program.
The following example is the pseudo code related to condition control in Python. Here, take the score ranking as an example to write the pseudo code related to the score ranking process. Note that here is the pseudo code, that is, the writing method of simulated code to show the specific execution process, not the real code.
1. Judgment of conditional statements
The following pseudo code is divided into three parts: if, elif and else. These three parts correspond to the above execution process of if – execute program – or – execute program – other situations – execute program. Of course, it is not necessarily these three situations. There are many situations that can be continuously divided. At this time, just add the elif conditional statement.
if Score less than 60: Fail elif The score is greater than or equal to 60 or less than or equal to 80: Rated as good else: Rated as excellent
Let's take the real code as the program execution. We judge many times and use multiple elif s for intermediate judgment. Finally, in other cases, we directly use else as the output. You can see that the final output of the example is actually the result we want. Here, note that the colon (:) must be added at the end of each conditional statement, and the execution process under each conditional statement needs to be preceded by four spaces.
a = 80 if a < 10: print('difference') elif a >= 10 and a < 60: print('fail,') elif a >= 60 and a < 80: print('good') else: print('excellent') # Output > > > excellent
2. Nested if
Then some people may think that they can judge how to deal with it according to other conditions. At this time, it is necessary to make nested judgment on if. Conditional judgment can nest multiple if, but it is generally not recommended to nest too much, otherwise the logic is too bad and it is not easy to judge.
a = 40 if a < 10: print('difference') elif a >= 10 and a < 60: if a >= 10 and a < 30: print('subordinate') elif a >= 30 and a < 50: print('intermediate') else: print('superior') elif a >= 60 and a < 80: print('good') else: print('excellent') # Output > > > intermediate
2, while loop control
1. while loop
Loop control literally means to conditionally loop a variable to obtain the desired result. In Python, the while keyword is used for loop control. Of course, if you want to control, you need to meet certain conditions to be called control. Therefore, a condition should be added after while to continuously judge a condition.
Here, the related pseudo code is used to represent the loop in the figure. The whole loop starts with conditions. When the conditions are met, the loop body (statements) are continuously executed. When the conditions are no longer met, the loop exits.
while [condition]: [statements]
We can see from the above example that the format of the loop is judgment condition + loop body (executed program), the result of judging the condition is True or False in Python, and True or False is represented by 1 and 0 respectively at the bottom. Therefore, when we want an unconditional loop, we can use True or 1 to represent a program whose condition is always satisfied to execute an infinite loop.
print(1 == True) print(0 == False) # Output > > > True True
2. Infinite cycle
Although True and 1 can be used to represent the condition of the loop in the condition option to execute the infinite loop, it will greatly waste unnecessary computing resources. In extreme cases, the infinite loop is easy to cause program crash. Therefore, in most cases, an interrupt condition judgment will be added to the infinite loop to prevent unnecessary accidents. Break is used as a keyword for the interruption of a loop, that is, in an infinite loop or a general loop, if you want to exit under a specific condition during the loop, you can add a break under the condition to terminate the loop.
You can see in the example that True and 1 are used as conditions to create an infinite loop, but a condition judgment is added to the loop body to exit the loop.
a = 1 while 1: a += 1 if a > 20: break print(a) # Output > > > 21 # ====================================================================================== b = 1 while True: b += 1 if b > 20: break print(b) # Output > > > 21
3. Cycles that do not meet the conditions
After the while loop judges that the conditions are not met, an else can be added to the loop as the final output of the loop.
a = 1 while a < 5: a += 1 else: print('Results after jumping out of the loop a:', a) # Output > > > Results after jumping out of the loop a: 5
This kind of else judgment that does not meet the conditions can ensure the output only without interrupting the cycle. Otherwise, if a cycle ends abnormally, the program in else cannot be executed. The following two methods are used to jump out of the loop: continue and break. You can see that the corresponding content can be output only when continue ends the loop normally, and break cannot obtain the output because it exits early.
a = 1 while a < 5: a += 1 if a < 3: break else: print('break Results after jumping out of the loop a:', a) # ====================================================================================== b = 1 while b < 5: b += 1 if b < 3: continue else: print('continue Results after jumping out of the loop b:', b) # Output > > > continue Results after jumping out of the loop b: 5
4. Loop out control continue and break
In Python, there are two keywords used to control the jump out of the loop. These two keywords are continue and break. The control effect of the two keywords on the jump out of the loop is different. Continue mainly jumps out of the loop, while break jumps out of the whole loop body. After that, all loops will not be carried out.
In the following example, when the conditions are met, use continue to jump out of this cycle, and the subsequent cycles will continue, so the final result will be 5, and break will interrupt the whole cycle, so a terminates the cycle when it reaches 3.
# Use break to terminate the loop a = 1 while a < 5: a += 1 if a == 3: break print(a) # Output > > > 3 # ====================================================================================== # Use continue to jump out of the current loop b = 1 while b < 5: b += 1 if b == 3: continue print(b) # Output > > > 5
3, for loop
1. Basic for loop
In fact, the for loop and the while loop are similar. The difference is that the while loop judges a certain condition, while the for loop mainly circulates continuously on a specific iteratable object. What are iteratable objects? They are lists, tuples, dictionaries, sets, and strings mentioned earlier. Here, take the List as an example. The basic form is the loop condition composed of the for and in keywords and the loop body in the loop. In the example, List all the elements in the List and print them.
list1 = {'Python', 'Java', 'C++'} for x in list1: print(x) # Output > > > Python C++ Java
2. for loop with else
Like the while loop with else, the code in else of the for loop must finish normally before it can continue to run. If the whole loop is not finished, the code in else will not continue to run. Here, the interrupt of the loop is also controlled by continue and break.
# break terminates the loop list2 = ['Python', 'Java', 'C++'] for i in list2: if i == 'Java': break print(i) else: print('Cycle end output') # Output > > > Python # ====================================================================================== # continue skips the current loop list2 = ['Python', 'Java', 'C++'] for i in list2: if i == 'Java': continue print(i) else: print('Cycle end output') # Output > > > Python C++ Cycle end output
summary
Conditional control (if) and loop control (while and for) are the two most basic parts of the program. These two controls will basically appear in the program. Moreover, these two controls do not have a difficult syntax structure, so you only need to remember the two steps of condition + execution.
In addition, we should pay attention to avoid the existence of infinite loop. If you jump out of the loop incorrectly, it may lead to program crash. At the same time, the else part of the loop must be output only when the loop ends normally. Unexpected exit or early termination of the loop can not run the else part normally.
key word | explain |
---|---|
if | For condition judgment |
while | For loops within conditions |
for | Loop that specifies the iteratable type |