繁体   English   中英

Python 中断嵌套的 for 循环并重新启动 while 循环

[英]Python break a nested for loop and restart the while loop

我创建了一个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

我不知道您粘贴代码的方式是否有错误,或者它最初是否也存在。 但是,while 循环之后的代码没有缩进。 好的,所以你在编辑中修复了这个问题。

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

然后,添加一个在while 循环开始后定义的变量breakloop设置为True。 它必须在 for 循环中设置为 False,而不是 folder_set。 在for循环之后,检查breakloop和break。 最终代码:

unacceptable = ['.', ',', '-', '(', ')', '*', '²', '=', '^', '$', ';', ':', '!', '§', '?', '/', '{', '}']

while True:
    breakloop = True
    folder = input('Enter folder here: ').lower()

    for i in unacceptable:
        if i in folder:
            print("Your folder name has a special character " + i + ", please make sure the folder name does not contain any special characters from:\n " + ' '.join(unacceptable) + ", or any other.")
            breakloop = False
            break

    if breakloop:
        break

编辑:我编辑了您的打印语句,并将其移到了while循环之外,因此不必为每次迭代重新定义。

我不是很喜欢 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

我希望这可以帮助你 !

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM