Introduction to the difference between if and elif in Python

Time：2022-5-7

Multiple if statements are judged separately each time

For example:

Example 1

?
 1 2 3 4 5 6 7 `a ``=` `5` `if` `a < ``6``:      ``#Condition 1` `    ``print``(``1``)` `if` `a < ``7``:      ``#Condition 2` `    ``print``(``2``)` `else``:` `    ``print``(``3``)`

Condition 1 and condition 2 are independent. In the first judgment, the value of a is less than 6, so the number 1 is printed. In the second judgment, the value of a is less than 7, so 2 is printed. If all if statements fail, they will be executed`else`The following statement, otherwise`else`Statement is not executed.

If condition 2 is changed to`elif`, the result is different

Example 2

?
 1 2 3 4 5 6 7 `a ``=` `5` `if` `a < ``6``:      ``#Condition 1` `    ``print``(``1``)` `elif` `a < ``7``:    ``#Condition 2` `    ``print``(``2``)` `else``:` `    ``print``(``3``)`

This time, condition 1 and condition 2 are related, that is, if condition 1 is judged successfully, condition 2 will not continue to judge. Conversely, if condition 1 fails, condition 2 will continue to be judged If both condition 1 and condition 2 fail, execute`else`The sentence inside.

The result of example 2 is obviously that only 1 will be printed.

Of course`if`and`elif`It’s OK to mix it up, but it looks strange and has poor readability

Example 3

?
 1 2 3 4 5 6 7 8 9 `a ``=` `5` `if` `a < ``6``:` `    ``print``(``1``)` `elif` `a < ``4``:` `    ``print``(``2``)` `if` `a < ``7``:` `    ``print``(``3``)` `else``:` `    ``print``(``4``)`

The results are: 1, 3

Application scenario:

• If you only want to execute one block of code, use`if-elif-else`Structure bar;
• If you want to run multiple code blocks, use multiple if. (multiple conditions are met at the same time)

This is the end of this article about the difference between if and elif in Python. For more information about the difference between if and elif in Python, please search the previous articles of developeppaper or continue to browse the relevant articles below. I hope you will support developeppaper in the future!

Ruffian Heng embedded: Super download algorithm rt-ufl v1 Use of 0 under IAR EW for arm

“Academic” project led by ruffian HengRt-ufl – Design of a super download algorithm for full platform i.mxrtv1. Version 0 has been released for nearly four months. Some customers have used this super download algorithm in the actual project development and debugging. At present, the feedback is OK, but this super download algorithm is far from […]