Send Close Add comments: (status displays here)
Got it!  This site "www.robinsnyder.com" uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.  Note: This appears on each machine/browser from which this site is accessed.
Python: Short circuit evaluation
by RS  admin@robinsnyder.com : 1024 x 640


1. Lua: Short circuit evaluation
Division (or remainder) by zero causes a run-time error and a program crash (for a C program).

What happens when the following program is run? There are three choices. Here is the Python code [#1]

Here is the output of the Python code.

What happened to the program crash?

2. Short circuit evaluation
In most programming languages, when one uses the conjunction operator or the disjunction operator a short-circuit evaluation takes place.

Short-circuit operators in Python:

3. Details
In a conjunction, if the first argument is false, then the entire conjunction is false, so there is no need to evaluate the second argument. But that argument might crash the program or have side-effects.

In a disjunction, if the first argument is true, then the entire disjunction is true, so there is no need to evaluate the second argument. But that argument might crash the program or have side-effects.

The above program is equivalent to the following program - which makes the short-circuit behavior more apparent. Here is the Python code [#2]

Here is the output of the Python code.


4. Disjunction
Here is the type of program but using disjunction instead of conjunction.

Here is the Python code [#3]

Here is the output of the Python code.


5. Disjunction program expanded
Here is the above program expanded to show the short-circuit evaluation.

Here is the Python code [#4]

Here is the output of the Python code.


6. Conjunction and disjunction
Whenever one writes "and" (in Python) or "or" (in Python) one must be aware (in the mind) of how that expression is evaluated in terms of the expanded program code.

Since it can be hard to think about this accurately (and quickly) it is often best to avoid the use of "and" and/or "or" in Python unless necessary and/or you know what you are doing.


7. End of page

by RS  admin@robinsnyder.com : 1024 x 640