How does break work in a for loop?

后端 未结 2 1281
失恋的感觉
失恋的感觉 2021-01-16 00:26

I am new in Python and I got confused about the way that \"break\" works in a for loop. There is an example in Python documentation(break and continue Statements) which calc

相关标签:
2条回答
  • 2021-01-16 00:44

    Try executing this code - it might make it more clear:

    for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(n, 'equals', x, '*', n//x)
            break
        print('loop still running...')
    else:
        # loop fell through without finding a factor
        print(n, 'is a prime number')
    

    vs:

    for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(n, 'equals', x, '*', n//x)
        break
        print('loop still running...')
    else:
        # loop fell through without finding a factor
        print(n, 'is a prime number')
    

    I'm sure the output would help you understand what is going on. #1 is breaking only if the if condition is satisfied, while #2 breaks always regardless of the if condition being satisfied or not.

    0 讨论(0)
  • 2021-01-16 00:47

    Sure - Simply put out-denting the "Break" means it's no longer subject to the "if" that precedes it.

    The code reads the if statement, acts on it, and then regardless of whether that if statement is true or false, it executes the "break" and drops out of the for loop.

    In the first example the code only drops out of the 'for' loop if the n%x==0 statement is true.

    0 讨论(0)
提交回复
热议问题