Search code examples
pythonreturnnonetype

How to check if function is trying to access something that doesn't exist?


i am working with python and i have this function:

c=15
def glteme(imgt):
    for a in range(0,80):            
        for b in range(0,80):
            if (imgt[a,b,0]==0 and imgt[a,b,1]==0 and imgt[a,b,2]==0):
                c=1
                return a,b,c

(I am working with image that is 80x80,and in these 2 for loops i am going through each pixel of image and try to find first black pixel).So,in this if condition i am checking if pixel of image is black,and if it is,then glteme(imgt) should return a,b,c.Then,i am trying to access c with glteme(imgt)[2] in code:

if glteme(imgt)[2]==1:
   ...

And when function returns a,b,c,it can access to c,but I don't know how to check if function can access c that doesn't exist?(and c doesn't exist if in above function,code never goes to if condition)I tried if glteme(imgt)[2]==False,if glteme(imgt)[2] is not True,etc,but it's not working..(I get error 'NoneType' object has no attribute '__getitem__' )Thanks in advance!


Solution

  • If I understand your question properly, your problem is to detect the condition when there is no black pixel in the image. As you have put your function, no return value is returned on this case.

    Change the function to return a guardian return value to signal no black pixel has been found, and check it on return:

    c=15
    def glteme(imgt):
        for a in range(0,80):            
            for b in range(0,80):
                if (imgt[a,b,0]==0 and imgt[a,b,1]==0 and imgt[a,b,2]==0):
                    c=1
                    return a,b,c
        return None  # This tells to the caller no result was found
    

    Later when calling this function check for None and act accordingly:

    res = glteme(imgt)
    
    if res is None:
        # ... no black pixel was found
    else:
        # ... do whatever with res, it will contain a, b, c