I am new the forum so hope this question is not too elementary or that it has been asked before. While writing some code in python, I found that individual functions (here called function1, function2 and function3) returning true or false would have the same output written to screen, and therefore I would like to link them together like this;
if function1 or function2 or function3:
print "something"
I know that function3 will take much more time to run, so I would like to avoid it. As the condition is now written it seems to me that it would be great for me if Python first evaluates function1 to false, and then stops the evaluation of the other conditions because it knows that the if-condition is already broken. The other possibility is that the returning values of all three functions are found separately before the truth value of the combined expression is evaluated. Does anybody know the sequences of action in the if condition-evaluation?
Python already does this for you with a mechanism known as “short-circuit” evaluation.
When a Boolean expression is found to be False (for an
and) or True (for anor) at any stage during the evaluation, the rest of the expression is not evaluated since the end-result is already determined at that point.So the order you put things into your Boolean expression really matters.
This is really quite useful since you can do something like this:
to avoid division by zero with a simple
andexpression (i.e., the division will never take place ifiis zero).Also, note: You do need
()for your function calls to work.Finally, this short-circuiting evaluation isn’t unique to Python, lots of languages do this.