0

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")
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245

1 Answers1

1

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")
Leonard
  • 783
  • 3
  • 22
  • that is a great approach thanks man i was doing a silly mistake I should casting user input into int – Souvik Sen Aug 31 '21 at 17:36
  • @SouvikSen Happy to help, and welcome to Stack Overflow. If this answer solved your issue, please mark it as accepted. – Leonard Aug 31 '21 at 17:38