Q:

Creating step function with error: The truth value of an array with more than one element is ambiguous

I am trying to make a box or step function using if/else statements. For example:
import matplotlib.pyplot as plt
import numpy as np

def V(x):
    if -1<=x<=1:
        return 20
    else:
        return 0
x=np.linspace(0,100)

plt.plot(x,V(x))

However, I get the error : 
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
I understand that this is because it is trying to compare all the x input values at once and cannot do so, but I don't understand why it doesn't just do one at a time and output the value for each. Indeed If i input just one x at a time it works. Is there an easy way to overcome this issue?

A:

Use map to apply your function to each value of x:
x = np.linspace(0, 100)
plt.plot(x, list(map(V, x)))

The reason for your error is you are attempting to apply a function on an entire array, when it is designed to work on a single element.
However, a better idea is to vectorise your function:
def V(x):
    res = np.zeros(len(x))
    res[np.where(np.abs(x)<1)] = 20
    return res

x = np.linspace(0, 100)
plt.plot(x, V(x))

