The difference between if and elif in Python

Time:2022-1-14

Multiple if statements are judged individually 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 value of a in the first judgment is less than 6, so the number 1 is printed. The value of a in the second judgment is less than 7, so 2 is printed. If all if statements fail, the statement after else will be executed. Otherwise, else statements will not be executed.

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

Example 2:

#Python learning exchange group: 778463939

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 the statements in else.

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

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

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 one block of code, use the if elif else structure;

  • If you want to run multiple code blocks, use multiple if. (multiple conditions are met at the same time)