pythonlinear-search

Linear search not returning expected output


I am tring a simple linear search in python but it is not working and i can not find what is wrong with my code!!!

n = input("enter a number: ")
arr = [1,42,3,45,5]
count = 0;
for i in range(0, len(arr)):
    if(arr[i] == n):
        count = count + 1
if(count>0):
    print("found")
else:
    print("not found")

Solution

  • The issue is this line if(arr[i] == n):: n is of type str so the comparison to an int will always fail.

    Try:

    if arr[i] == int(n):
    

    Here, you are casting n to an integer before the comparison. Please note that this will throw an error if you cannot cast to an int. You could solve this as follows:

    n = input("enter a number: ")
    arr = [1, 42, 3, 45, 5]
    
    try:
        if int(n) in arr:
            print("found")
        else:
            print("not found")
    
    except ValueError:
        print("Not an integer")