Introduction to the difference between if and elif in python

  • 2021-12-12 08:55:51
  • OfStack

Multiple if statements are judged separately each time

For example:

Example 1


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. The number 1 is printed when the value of a is judged to be less than 6 for the first time, and the number 2 is printed when the value of a is judged to be less than 7 for the second time. If all if statements fail, they will be executed else Otherwise, the statement after the else Statement is not executed.

If Condition 2 is modified to elif The result is different

Example 2


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 successful, Condition 2 will not continue to judge. Conversely, if Condition 1 determines failure, then Condition 2 continues to be determined. If Condition 1 and Condition 2 both determine failure, then execution else The sentences 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, but it looks strange and is poorly readable

Example 3


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 1 code block, use the if-elif-else Structure bar; If you want to run multiple blocks of code, use multiple if. (Multiple conditions are satisfied at the same time)

Related articles: