繁体   English   中英

中断嵌套的for循环后继续while循环

[英]Continuing a while loop after breaking a nested for loop

在嵌套嵌套循环中满足某些条件之后,我正在寻找一种更pythonic的方式来继续while循环。 对我有用的非常笨拙的代码是:

tens = ['30','40','50','60','70','80','90','00']
z=0
while z==0:
    num = input('Please enter a number: ')
    z=1    
    for x in tens:
        if num[0]=='0' or x in num:
            print('That was an invalid selection, please try again.\n')
            z=0  # There has GOT to be a better way to do this!
            break
print(num+' works, Thank You!')

我可以使用try / except来回答这个问题

tens = ['30','40','50','60','70','80','90','00']
while True:
    num = input('Please enter a number: ')  
    try:
        for x in tens:
            if num[0]=='0' or x in num:
                print('That was an invalid selection, please try again.\n')
                raise StopIteration
    except:
        continue
    break
print(num+' works, Thank You!')

我面临的挑战是

a)在满足if的情况下继续while循环(请求新输入)(换句话说,中断for循环并在同一步骤中继续while循环)

b)在测试每个新输入时,从头开始运行可迭代的十位。

注意:此问题与Reddit Challenge#246 字母拆分有关

更新:合并了HåkenLid提供的答案,代码变为

tens = ['30','40','50','60','70','80','90','00']
while True:
    num = input('Please enter a number: ')
    if num[0]=='0' or any(t in num for t in tens):
        print('That was an invalid selection, please try again.\n')
        continue
    break
print(num+' works, Thank You!')

我还没有解决“从嵌套的for循环中中断/继续”的问题,但是用any()函数代替循环肯定对我有用。

不需要您的for循环。 只需in关键字中使用。 但是除此之外,您可以使用break很好。

tens = ['30','40','50','60','70','80','90','00']
while True:
    num = input('Please enter a number: ')
    if num in tens:
       break
    print('That was invalid selection, please try again.\n')
print(num+' works, Thank You!')

在大多数情况下,具有嵌套循环是不好的设计。

您的功能应始终尽可能小。 遵循该规则,您将永远不会违反SOLID(单一负责原则)的第一条规则。

您的代码可能如下所示:

tens = ['30','40','50','60','70','80','90','00']

def main():
    while 1:
        num = input('Please enter a number: ')
        if nested_test(num):
            print('That was an invalid selection, please try again.\n')
            break

def nested_test(num):
    for x in tens:
        if <some test>:
            return True

暂无
暂无

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

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