A notable feature is that the flow of control continues "downward". In the simple if/else flow shown here, is the condition evaluated in the diamond results in a True, the "if branch" is executed.
If the condition evaluated in the diamond results in a False, the "else branch" is executed.
If there were two or more subsequent ifs, then all would get evaluated, i.e.
if test_exp1:
statement 1
if test_exp2:
statement 2
if test_exp2:
statement 3
but only get executed if the expression results in a True
In a sequence of code such as:
if test_exp1:
statement 1
elif test_exp2:
statement 2
elif test_exp2:
statement 3
else:
body_of_else
if the if, or a subsequent elif evaluates to True, then that branch gets executed. If all evaluate to False, then and only then would the else block - if used - get executed.
This allows the use of bounded values: e.g. if checking grades, and the first check is for < 50, if the next check is looking for a grade between 50 and < 65, sequential ifs are much less convenient than an if/elif/else block.
# using if and elif is simpler
if grade < 50:
return "Fail"
elif grade < 65:
return "Merit"
# sequential ifs add some complexity and
# all if statements get tested.
if grade < 50:
return "Fail"
if grade >=50 and grade < 65:
return "Merit"
a if condition else b # expression syntax
Think of the conditional expression as switching between two values. It is very useful when you're in a 'one value or another' situation, it but doesn't do much else.
result = "Pass" if grade >= 50 else "Fail"
If you need to use statements, you have to use a normal if statement instead of a conditional expression. If you're having trouble remembering the order, then remember that when read aloud, you (almost) say what you mean.
For example, x = 4 if b > 8 else 9 is read aloud as x will be 4 if b is greater than 8 otherwise 9.
Official documentation: