我的问题如下:
def searchWordlist():
path = str(raw_input(PATH))
word = str(raw_input(WORD))
with open(path) as f:
for line in f:
if word in line:
print "Word found"
比我添加以下代码:
else:
print "Word not found"
但这显然行不通,因为它会打印“未找到单词”,直到找到单词为止。好吧..但是我怎么能打印出找不到这个词呢?!我真的不知道。
提前致谢!
最佳答案
Python 对这种事情有一个特殊的技巧:
for line in f:
if word in line:
print "Word found"
break
else:
print "Word not found"
这里的 else
与 for
一起使用,如果循环正常完成而没有遇到 break
则专门执行。
关于Python逐行检查列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41107626/