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 executedelseThe following statement, otherwiseelseStatement is not executed.

If condition 2 is changed toelif, 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, executeelseThe sentence inside.

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

Of courseifandelifIt’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, useif-elif-elseStructure 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!