Hi am new to python here is what am trying to do , i have this below list.
x= [1,2,3,4,5,6,7,8,9]
and here is my python code:
length = len(x)
c = input("Enter a no\n")
for i in range (length):
if x[i] == c:
print ("Found at position ", i)
else:
print("not found")
and the output am receiving.
Enter a no
2
not found
not found
not found
not found
not found
not found
not found
not found
not found
Now with my very few little knowledge what i figured out is this multiple not found is happening because every time loop takes a no checks with the list and if its not available its moving to else part due to lack no proper beak
statement but what am not able to figure out that when it takes to in x[i] its matching then output should be Found at position 1
. i read somewhere need to use if c in x[i]
but it didn't work. on the hand i re-wrote the code.
def ls():
t = int(input("Enter your search no \n"))
for i in x:
if i!= t:
continue
print("Your value is present in ")
break
else:
print ("parrrrrrrrrrr")
ls()
which is working all good. It will be of help if i can get to know:
- with 1st program why its showing not found even the input is present in the list
- the part where c in x[i] was entered same issue happened as per my knowing (which now makes no-sense) it should also work
- if it is the case of integer vs list then how my 2nd code is working -is it the rigt way to do linear search.
str
object and then compared withint
object without implicit conversion, so the expression always beFalse
.c in x
where x is a list works, butx[i]
is an integer in your caseint
implicitlyThe most elegant way in my opinion is:
And of course dont forget to catch ValueError if input is not convertable into integer