我有我的代码,但它似乎没有按预期工作。它需要向用户请求输入来搜索一个文件,一旦找到就不再询问,而是继续询问。但是我想让它再次询问用户是否还没有找到文件。我的代码如下:
import os, sys
from stat import *
from os.path import join
while True:
lookfor=input("\nPlease enter file name and extension for search? \n")
for root, dirs, files in os.walk("C:\\"):
print("Searching", root)
if lookfor in files:
print("Found %s" % join(root, lookfor))
break
else:
print ("File not found, please try again")
break
只是中止内部for循环。您可以简单地使用助手变量:或者,将其设为函数并使用
return
:也可以使用^{} construct :
break
在for循环中,因此它只会将您从for循环中分离出来,而不是while
循环。你知道吗问题是你只打破了内部循环(即
for
)。你知道吗您可以将其放入函数中并返回而不是中断,或者引发并捕获异常,如下所示:Breaking out of nested loops
相关问题 更多 >
编程相关推荐