如何从内循环到外循环的开头

时间:2017-10-23 11:13:32

标签: python

什么是打破内循环的最好方法,所以我到达外循环的开头

fgets(wszFileName, PATH_MAXLEN, stdin);

现在我有点像

while condition:
    while second_condition:
        if some_condition_here:
            get_to_the_beginning_of_first_loop

2 个答案:

答案 0 :(得分:7)

Python可以为else:循环选择while子句。如果您调用break,则会调用此方法,因此这些是等效的:

while condition:
    while second_condition:
        if condition1:
            break
    if condition1:
        continue
    do_something_if_no_break()

while condition:
    while second_condition:
        if condition1:
            break
    else:
        do_something_if_no_break()

答案 1 :(得分:0)

您只需使用@ArthurTacca的答案为基础,就可以使用Python的else运算符来实现优雅的任意深度中断功能:

# Copied from ArthurTacca
while condition:
    while second_condition:
        if condition1:
            break
    else:
        do_something_if_no_break()
        # Minor addition
        continue  # This avoids the break below
    break  # Fires if the inner loop hit a "break"

请注意,else:continue / break模式可以重复到任意深度,也可以用于for循环。