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:
str
object and then compared with int
object without implicit conversion, so the expression always be False
.c in x
where x is a list works, but x[i]
is an integer in your caseint
implicitlyThe most elegant way in my opinion is:
c = input("Enter a no\n")
items = [1,2,3]
print(items.index(int(c)) if int(c) in items else 'Not found')
And of course dont forget to catch ValueError if input is not convertable into integer