print if else statement on python

后端 未结 2 1742
伪装坚强ぢ
伪装坚强ぢ 2021-01-26 01:27

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\");
clas         


        
相关标签:
2条回答
  • 2021-01-26 02:21

    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" 
    
    0 讨论(0)
  • 2021-01-26 02:32
    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."
    
    0 讨论(0)
提交回复
热议问题