Question

I always had this curiosity about Python and I can't find a clear answer, maybe someone can help me what is the "if", "elif" and "else" priority and way of working? if I do:

if conditionA:
    do something
elif conditionB:
    do something else
else:
    do something else

does the "else" check the condition in "elif" or both conditions "if" and "elif"? is there any interesting order in which they can be used (e.g. if, else, elif, else etc.) ? thanks

Was it helpful?

Solution

else is the catch-all after all the if and elif statements were false. Putting it in the middle would be a syntax error.

Don't think of the else "checking the conditions." Think of it as the control flow never even reaches the else if the others were true. The same is true for multiple elif.

Consider this:

if False:
    print 'first'
elif True:
    print 'second'
elif True:
    print 'third'

Even third won't print, because the second one was true. It doesn't matter that the third was true, because it's not even evaluated.

This can have some side effects too, if you're calling functions:

if send_email(to_coworker):
    pass
elif send_email(to_boss):
    pass

Assuming the function returns True if it succeeds, the email to your boss will only send if the email to your coworker fails, even though the function would need to be called to evaluate the elif condition

OTHER TIPS

They're processed in the order that they're encountered in the file.

if True:
  # Always executes.
elif False:
  # Is never checked.
else:
  # We never get this far, either.

As soon as the first condition that evaluates True is encountered the corresponding block of code is executed. Additional conditions aren't checked.

They don't have priorities for itself, what really matters is the order, so the first condition will be checked and if the first condition is False than the second condition is checked and so on until any condition is True or it executes the else statement if and only if all conditions where False

In your example if conditionA is True then the code inside the if statement will be executed and the elif and else conditions will not matter at all.

If conditionA is False and conditionB is True than the code inside the elif statement will be executed.

Finally only when the conditionA and conditionB is False then the code inside else block will be executed

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top