python - Linear Search - Matching integer with list -


hi new python here trying , have below list.

x= [1,2,3,4,5,6,7,8,9] 

and here python code:

length = len(x) c = input("enter no\n")  in range (length):     if  x[i] == c:         print ("found @ position ", i)     else:         print("not found") 

and output receiving.

enter no 2 not found not found not found not found not found not found not found not found not found 

now few little knowledge figured out multiple not found happening because every time loop takes no checks list , if not available moving else part due lack no proper beak statement but not able figure out when takes in x[i] matching output should found @ position 1 . read somewhere need use if c in x[i] didn't work. on hand re-wrote code.

def ls():     t = int(input("enter search no \n"))     in x:         if i!= t:             continue         print("your value present in ")          break     else:         print ("parrrrrrrrrrr")  ls() 

which working good. of if can know:

  • with 1st program why showing not found input present in list
  • the part c in x[i] entered same issue happened per knowing (which makes no-sense) should work
  • if case of integer vs list how 2nd code working -is rigt way linear search.

  1. because input returns str object , compared int object without implicit conversion, expression false.
  2. c in x x list works, x[i] integer in case
  3. 2nd code working because convert input int implicitly

the elegant way in opinion is:

c = input("enter no\n") items = [1,2,3] print(items.index(int(c)) if int(c) in items else 'not found') 

and of course dont forget catch valueerror if input not convertable integer


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -