2014-11-25 145 views
0

else else語句有問題。如何使代碼打印找不到?它保持打印未發現如果在Python上打印if語句

import os 

f = open('D:/Workspace/snacks.txt', "r"); 
class line: 
    for line in f.readlines(): 
     if line.find('chocolate') != -1: 
      print "found ", line 
     elif line.find('milkshake') != -1: 
      print "found ", line 
     else: 
      print "not found" 
+0

您TRID印刷線?你確定這些詞不是按行列出的嗎? – Beri 2014-11-25 08:14:41

+3

我不確定'class line:'在這裏做什麼。刪除它,它應該工作得很好。請記住隨後關閉文件。 – 2014-11-25 08:15:53

+0

它是這樣的,它會首先尋找巧克力,然後只有奶昔,如果都沒有找到只有那麼它會打印「找不到」 – pad 2014-11-25 08:16:44

回答

1

所有你需要關閉文件首先,你可以包裝使用,使蟒蛇照顧它。刪除類行。其餘的代碼看起來很好。

import os 

with open('D:/Workspace/snacks.txt', "r") as f: 
    for line in f.readlines(): 
     if line.find('chocolate') != -1 or line.find('milkshake') != -1: 
      print "found ", line 
     else: 
      print "not found" 
+0

如果你想使這個片段的類方法,首先你需要創建一個方法的定義:)其次clas名稱由UpperCase開始。 – Beri 2014-11-25 08:18:25

2
with open('foo') as f: 
    lines = f.readlines() 
    for line in lines: 
     if 'chocolate' in line.lower(): 
      print "Found: ", line 
     elif 'milkshake' in line.lower(): 
      print "Found: ", line 
     else: 
      print "Not Found."