020讲求助小细节求助。
以下代码是020关于判断 各种括号是否合法的部分代码。s = []
for i in range(6):
temp = input('请输入测试字符串:')
if temp not in ['(', ')', '{', '}', '[', ']']:
print('请不要输入括号意外的字符')
continue
else:
s.append(temp)
现在遇到的问题是这样子的。
这是一个需要循环6次的循环。 我希望获取的内容是“(){}[]” 这六个括号。 用这个代码的话, 假如我其中一次输入的不是括号, 是其他的东西的话, 它接下去会再循环5次就结束了。
怎么改才能让他的循环不算上出错的那一次, 接着把6个括号给输入完?
{:5_104:}
可以套个while 循环,将 if 中的 continue 删除,在 else 中添加 break,参考代码:
s = []
for i in range(6):
while 1:
temp = input('请输入测试字符串:')
if temp not in ['(', ')', '{', '}', '[', ']']:
print('请不要输入括号意外的字符')
else:
s.append(temp)
break
或者直接用 while 循环,外部用一个 count 记录执行次数,若不符合条件则 count 不增加,反之 +1
s = []
count = 0
while count < 6:
temp = input('请输入测试字符串:')
if temp not in ['(', ')', '{', '}', '[', ']']:
print('请不要输入括号意外的字符')
else:
s.append(temp)
count += 1 Twilight6 发表于 2022-4-29 17:05
可以套个while 循环,将 if 中的 continue 删除,在 else 中添加 break,参考代码:
Genius! 瑞思拜!{:5_108:}
页:
[1]