在python上打印if else语句

时间:2014-11-25 08:12:19

标签: python

我的else语句有问题。如何找不到代码打印?它保持打印未找到

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" 

2 个答案:

答案 0 :(得分: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."

答案 1 :(得分:1)

首先你需要关闭你的文件,你可以使用包装器让python为你处理它。删除类行。其余的代码看起来很好。

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"