【发布时间】:2020-05-21 04:39:00
【问题描述】:
我创建了一个小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
【问题讨论】:
-
您需要将
folder_set设置为true,以便在满足条件且其中还有错字的情况下中断while 循环。 -
我希望打破
for循环而不是 while -
您根本不需要 for 循环。使用集合交集:
bad=set(inacceptible) & set(folder); if bad: folder_set=True; print(bad)(注意在一个作业中有一个=)。 -
使用
break而不是continue来打破循环。如果breakloop未定义,则意味着其中一个 for 没有任何可迭代的内容,如果从未为真,则您正试图在其范围之外使用breakloop。
标签: python loops while-loop restart continue