0

I am getting 2 different errors when I run the code below, which are motioned below. I am trying to return a Nonetype or a numpy array from the func(value) function. it is required to use a.any() or a.all() whilst testing empty numpy arrays but it gives an error when A is None since a.any() or a.all() is not a valid function for Nonetype. how could i make the code below work?

import numpy as np

def func(value):
    if value == 1:
        A= np.array([12,3,4,55,6,12,3])
    else:
        A= None
    return A

for n in range(2):
    output = func(n)
    if output != None:
        print("None type")
    else:
        print("None")

Error when if if output != None

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Error when if if output.any() != None

AttributeError: 'NoneType' object has no attribute 'any'
tony selcuk
  • 709
  • 3
  • 11
  • You want `if output is not None`. Writing `output != None` when `output` is an `ndarray` uses `ndarrays.__ne__` to make the comparison, which creates of matrix of bools, hence the first error. The second fails when `output` is `None` for the obvious reason stated in the error message. – Brian61354270 Jun 19 '21 at 01:46
  • For more on why you should always prefer using `is` instead of `==` when checking for `None`, see [What is the difference between "is None" and "== None"](https://stackoverflow.com/questions/3257919/what-is-the-difference-between-is-none-and-none) and [In python, why 'is' is preferred over '==' for checking if object in None](https://stackoverflow.com/questions/31268288/) – Brian61354270 Jun 19 '21 at 01:48

0 Answers0