2017-12-09 5 views
-6

誰でもこのコードがうまくいかない理由を教えてください。リストからアイテムを検索するには?

lst=[5,9,2,5,13] 
item = int(input("Please enter the search item.")) 
found = False 
for search in range(len(lst)): 
    if item == (lst[search]): 
     found = True 
if found: 
    print('{} is in the list'.format(item)) 
else: 
    print('{} is not in the list'.format(item)) 
+4

それは本当にPythonのではないので、それが動作しないことができます。構造化チュートリアルを強くお勧めします。 https://sopython.com/wiki/What_tutorial_should_I_read%3F – jonrsharpe

答えて

1

あなたは、少なくとも同じように、より良い方法で記述する必要があります。最初にチュートリアルを参照することをお勧めします。

しかし、これはあなたのリストの要素を検索することができます方法です。

list=[5,9,2,5,13] 
element = raw_input("Please enter the desired element") 

if int(element) in list: #note i've put int() because your list is made out of numbers rather than strings. 
    print element + " is in the list" 
else: 
    print element + " is not in the list" 
+0

リストをループするために 'range(len(lst))'を使うことは_pythonic_とはみなされません。 – Matthias

0

私は構文について、それが実際のpythonであるかを確認していない:

list=[5,9,2,5,13] 
item=input("Please enter the search item.") 
found=false 
for search = 0 to list.length -1 
if item==list[search]: 
found= True 
next search 
if found==True: 
print("The item is in the list.") 
else: 
    print("The item is not in the list.") 
-1

あなたが求めている何が:

value = int(input('Please enter a value to search: ')) 

if value in [5, 9, 2, 5, 13]: 
    print('Item found.') 
else: 
    print('Item not found.') 
関連する問題