Why i am getting none as output in this code?

def linear_search(data,value):
    for i in range(len(data)):
        if data[i]==value:
            return i
        
    return print("not found")
        
        
data=[12,45,67,89,9,3]
x=linear_search(data,14)
print(x)

*******OUTPUT

not found
None
1 Like

Hi there, welcome to the forums.

It has to do with your final line of the function:

return print("not found")

In your example, you’re searching for the value 14 in the provided data list ([12,45,67,89,9,3]).

As this value is not in the list, we never satisfy the criteria of your if statement and so we return the line I quoted above.

This has the effect of printing to the console the line not found, as you see in the output.

However, the print() function itself returns a None type… which you’re then returning again out of your linear_search function.

So, in the final line:

    return print("not found")

we are capturing the None returned by the call to print(), and returning it from the function.

You subsequently print the return value of linear_search here:

data=[12,45,67,89,9,3]
x=linear_search(data,14)
print(x)

… and as the return is None, print(x) writes None to the console.

Does that make sense?

5 Likes

Thank you very much … I got it from your explanation!

1 Like