Comparison of usage of python break and continue

  • 2021-11-10 10:24:35
  • OfStack

Comparative description

1. break and continue are two keywords of python

2. break and continue can only be used in loops

3. break terminates the execution of the loop, that is, when the loop code encounters break, it will no longer loop. continue is to end this loop and continue to the next loop, that is, the remaining code of this loop will no longer execute, but will proceed to the next loop.

Instances

Break


#  Have 5 An apple 
# 1.  Eat 3 After an apple ,  Be full . The subsequent apples are not eaten 
# 2.  Eat 3 After an apple . Eat first 4 An apple , Found half a worm , Don't eat this apple , And eat the leftover apples 
 
for i in range(1, 6):
    if i == 4:
        print(' Be full ,  Don't eat ')
        break  #  Terminate the execution of the loop 
    print(f' Eating labeled  {i}  Apple ')

continue


#  Have 5 An apple 
# 1.  Eat 3 After an apple ,  Be full . The subsequent apples are not eaten 
# 2.  Eat 3 After an apple . Eat first 4 An apple , Found half a worm , Don't eat this apple , And eat the leftover apples 
 
for i in range(1, 6):
    if i == 4:
        print(' Found half a worm , Don't eat this apple ,  Not having enough to eat , Keep eating the leftovers ')
        continue  #  This loop ends , Continue 1 Sub-cycle 
 
    print(f' I ate it numbered {i} Apple ')

Basic knowledge points:

Python break statement

The Python break statement, as in the C language, breaks the minimum closed for or while loop.

The break statement is used to terminate the loop statement, which stops the execution of the loop statement if the loop condition does not have the False condition or if the sequence has not been completely recursive.
The break statement is used in the while and for loops.


Related articles: