2017-12-12 7 views
-3

を発見されない場合は、「何の結果を」印刷しないする必要があり、私は「何の成果」を印刷しないことができるようにする必要がありは、私は何もPythonのファイルを検索するには

**strong text**elif x.upper()=="Y": 
    k=input("Enter the 1st letter of the name (upper-Case):") 
    y=open("Names.txt","r") 
    for i in y.readlines(): 
     if k.upper() in i: 
      print (i[:-1]) 
     #need option if no search results are found 
+2

それもそうです。あなたを止めているのは何ですか? – Ivan

+0

フラグが見つかった場合( 'found'の中に' found = True'のようなものがあります)、フラグがfalseならば 'for'の外側に '結果がありません'を出力します – depperm

+0

もう一つのオプションはfor print文の後ろにループして壊れます(1つの検索結果が必要な場合のみ)。 – Matt234

答えて

3
**strong text**elif x.upper()=="Y": 
k=input("Enter the 1st letter of the name (upper-Case):") 
y=open("Names.txt","r") 
found = False 
for i in y.readlines(): 
    if k.upper() in i: 
     print (i[:-1]) 
     found = True 
if not found: 
    print("no results") 
0
**strong text**elif x.upper()=="Y": 
    k=input("Enter the 1st letter of the name (upper-Case):") 
    y=open("Names.txt","r") 
    all_lines = y.readlines() 
    for i in all_lines: 
     if k.upper() in i: 
      print (i[:-1]) 
     #need option if no search results are found 
    found_f = k.upper() in ''.join(all_lines) 

ファイル全体をワンショットで検索できます。最高のパフォーマンスではありませんが、実行するのに十分シンプルです。それはあなたのコードの変更を最小限にしようとしていました。私はそうするでしょう:

**strong text**elif x.upper()=="Y": 
    k=input("Enter the 1st letter of the name (upper-Case):") 
    y=open("Names.txt","r") 
    all_text = y.read() 
    for i in all_text.splitlines(): 
     if k.upper() in i: 
      print (i) # don't need [:-1] anymore 
     #need option if no search results are found 
    found_f = k.upper() in all_text 
関連する問題