Python程序在不需要的时候不断循环

2024-09-25 00:30:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有我的代码,但它似乎没有按预期工作。它需要向用户请求输入来搜索一个文件,一旦找到就不再询问,而是继续询问。但是我想让它再次询问用户是否还没有找到文件。我的代码如下:

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")

Tags: 文件代码用户infromimportforos
3条回答

break只是中止内部for循环。您可以简单地使用助手变量:

import os, sys

while True:
    lookfor=input("\nPlease enter file name and extension for search? \n")
    found = False
    for root, dirs, files in os.walk("C:\\"):
        print("Searching", root)
        if lookfor in files:
            print("Found %s" % os.path.join(root, lookfor))
            found = True
            break
     if found:
         break
     print ("File not found, please try again")

或者,将其设为函数并使用return

def search():
    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" % os.path.join(root, lookfor))
                return
        print ("File not found, please try again")
search()

也可以使用^{} construct

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" % os.path.join(root, lookfor))
            break
    else:
        print ("File not found, please try again")
        continue
    break

break在for循环中,因此它只会将您从for循环中分离出来,而不是while循环。你知道吗

import os, sys
from stat import *
from os.path import join

condition=True 

while condition:
    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))
            condition = False      #set condition to False and then break
            break
        else:
            print ("File not found, please try again")

问题是你只打破了内部循环(即for)。你知道吗

您可以将其放入函数中并返回而不是中断,或者引发并捕获异常,如下所示:Breaking out of nested loops

相关问题 更多 >