Python打破嵌套的for循环并重新启动while循环

问题描述 投票:0回答:2

我创建了一个小while循环来检查列表中是否有任何特殊字符在文件夹名称中。我想让它在检测到第一个字符时停止重复for循环,然后重新启动while

folder_set = False
while folder_set == False:
    inacceptable = ['.', ',', '-', '(', ')', '*', '²', '=', '^', '$', ';', 
    ':', '!', '§', '?', '/', '{', '}']
    folder = input('Enter folder here: ').lower()
    for i in inacceptable:
        if i in folder:
            print(f'Your folder name has a special character {i}, please make 
            sure the folder name does not contain any special character:\n {" 
            ".join(inacceptable)}, or any other special character.')
            folder_set == False
            breakloop = 'continue'
            continue
    folder_path = os.path.join(os.getcwd(), str(folder))
    if os.path.isdir(folder_path) == True:
        confirmation = input('Folder already exists, would you like to save 
        your files in it? (yes/no) ', )
    if confirmation.lower() == 'yes':
        folder_set = True
    else:
        folder_set = True

但是它不起作用。你能解释为什么吗?另外,如果我尝试打印breakloop变量,则会收到错误breakloop not defined

python loops while-loop restart continue
2个回答
0
投票

我不知道您粘贴代码的方式是否有误,或者最初是否也存在。但是,while循环后的代码不会缩进。好的,您已在编辑中修复了它。

您不需要在for循环中继续,而是在那儿中断并删除行folder_set == False

然后,在while循环开始后添加一个定义为True的变量breakloop。必须在for循环中将其设置为False,而不是folder_set。在for循环之后,添加以下行:

if breakloop:
    break

0
投票

我不是真的对Python感兴趣,但我建议您制作folder_set = true或将其删除,因为您将其设置为false,如果while为false,则意味着它将永远不会进入它进行迭代,我建议的另一件事是:

inacceptable = ['.', ',', '-', '(', ')', '*', '²', '=', '^', '$', ';', ':', '!', '§', '?', '/', '{', '}']
folder = input('Enter folder here: ').lower()
for i in inacceptable:
    if i in folder:
        print(f'Your folder name has a special character {i}, please make sure the folder name does not contain any special character:\n {" ".join(inacceptable)}, or any other special character.')
        break

希望对您有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.