mweeks@air:Desktop$ cat short_circuit.py # Writen by Michael Weeks to illustrate short-cirucit evaluation. # # Begin lines from # https://jakevdp.github.io/PythonDataScienceHandbook/02.02- # the-basics-of-numpy-arrays.html import numpy as np np.random.seed(0) # seed for reproducibility x1 = np.random.randint(10, size=6) # One-dimensional array # End lines from # https://jakevdp.github.io/PythonDataScienceHandbook/02.02- # the-basics-of-numpy-arrays.html xlen = x1.size; print("xlen is ", xlen) xindex = 5; if (x1[xindex] == 4): print("x1[", xindex, "] is four") else: print("x1[", xindex, "] is not four") xindex = xindex + 1; # Note: xindex is now out-of-bounds # The next if block works if ((xindex < xlen) and (x1[xindex] == 4)): print("x1[", xindex, "] is four") else: print("x1[", xindex, "] is not four") print("About to cause an error") if ((x1[xindex] == 4) and (xindex < xlen)): print("x1[", xindex, "] is four") else: print("x1[", xindex, "] is not four") mweeks@air:Desktop$ mweeks@air:Desktop$ python short_circuit.py xlen is 6 x1[ 5 ] is not four x1[ 6 ] is not four About to cause an error Traceback (most recent call last): File "/Users/mweeks/Desktop/short_circuit.py", line 34, in if ((x1[xindex] == 4) and (xindex < xlen)): ~~^^^^^^^^ IndexError: index 6 is out of bounds for axis 0 with size 6 mweeks@air:Desktop$