0

I have a problem with else statement. How to make the code print not found? it keep print not found

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" 
4
  • You trid printing the lines? Are you sure those words are not present in lines? Commented Nov 25, 2014 at 8:14
  • 3
    I'm not sure what class line: does here. Remove it and it should work just fine. Remember to close file afterwards. Commented Nov 25, 2014 at 8:15
  • The way it is, it will first look for chocolate, only then milkshake, and if neither are found only then will it print "not found" Commented Nov 25, 2014 at 8:16
  • Is there any way to do it? I already remove the class line: but it still repeat print not found Commented Nov 25, 2014 at 9:33

2 Answers 2

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."
Sign up to request clarification or add additional context in comments.

Comments

1

First of all you need to close your file, you can use with wrapper to make python take care of it for you. Remove the class line. Rest of the code looks fine.

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" 

1 Comment

If you wanted to make this snippet a class method, first you need to create a mathod definition:) Secondly clas names start by UpperCase.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.