python - What is the function of elif? -
if wanted check multiple conditions, can't use multiple if statements? example:
a = 10 b = 20 if == b: print('equal') if < b: print('less') if > b: print('greater')
using multiple if statements evaluate every if
condition. conditions in example mutual exclusive, might have similar result. however, if a
or b
changes in-between, condition might become true:
a = 5 b = 7 if < b: = b if == b: b += 1
both conditions evalute true , executed. might not intended, use:
a = 5 b = 7 if < b: = b elif == b: b += 1
will execute first condition.
even mutual exclusive conditions example, every expression has evaluated, slower second variant.
note elif
(aka else if
) identical to:
if <cond1>: pass else: if <cond2>: pass else: if <cond3>: pass
as can see, result in tests run out of text , less readable than:
if <cond1>: pass elif <cond2>: pass ...
this more expressive, reader has not check conditions mutual exclusive. semantics clear beginning.
finally:
something like:
i = 1 if none: k = 5 elif not (i <= 0): k =
will not work using example.
Comments
Post a Comment