在打破嵌套for循环后继续while循环

时间:2016-01-31 16:48:59

标签: python for-loop

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

this is the subgraph-node:
(<__main__.XGraph object at 0xb5ec21ac>, {})
these are its internal nodes:
1
2
3
this is an atomic node:
(4, {})
this is an atomic node:
(5, {})

我可以在this question中使用try / except:

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!')

我面临的挑战是

a)当满足if时继续while循环(请求新输入)(换句话说,打破for循环并在同一步骤中继续while循环)

b)每次测试新输入时,从头开始运行十次迭代。

注意:此问题与Reddit Challenge#246 Letter Splits

有关

更新:纳入HåkenLid提供的答案,代码变为

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!')

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

2 个答案:

答案 0 :(得分:0)

不需要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!')

答案 1 :(得分:0)

在大多数情况下,嵌套循环是糟糕的设计。

您的功能应尽可能小。适用于该规则,您永远不会破坏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