Controlling Logic Flow Inside Loops
In loops, break and continue are keywords used to control the execution flow of the loop.
break immediately terminates the loop, while continue skips the current iteration and proceeds to the next one.
What is the break Keyword?
The break keyword is used to immediately exit a loop when a certain condition is met.
For example, the while loop below has a condition count < 10, but the loop exits when count is 5.
count = 0 while count < 10: print(count) # Increment count by 1 count += 1 # When count equals 5 if count == 5: # Exit the loop break
Running this code will stop the loop when count reaches 5, resulting in the following output:
0 1 2 3 4
What is the continue Keyword?
The continue keyword immediately ends the current iteration and proceeds to the next iteration of the loop.
count = 0 while count < 5: # Increment count by 1 count += 1 # When count equals 3 if count == 3: # Skip to the next iteration continue print(count)
When this code is executed, the iteration where count equals 3 is skipped due to the continue keyword, producing the following output:
1 2 4 5
As shown above, utilizing the break and continue keywords allows you to control the logic flow within loops based on the specific conditions.
Lessons in this chapter · While Loops and List Comprehensions
- 1. How to Execute a Loop While a Given Condition is True
- 2. Controlling Logic Flow Inside Loops
- 3. Using While Loops with Lists
- 4. Multiple-choice quiz
- 5. Calculating Minimum, Maximum, and Sum
- 6. How to Reverse the Order of Objects
- 7. Iterating Over Elements of an Iterable
- 8. Iterating Over Key-Value Pairs with the items() Function
- 9. Simplifying Lists with List Comprehensions
- 10. Using the join() Function to Concatenate Strings
- 11. Differences Between Iterables and Iterators
- 12. Coding Quiz - Determine Odd/Even
- 13. Multiple-choice quiz
- 14. Fill-in-the-blank quiz
What is the function of the break keyword in a while loop?
Skips the current iteration.
Executes the loop's code in reverse.
Terminates the loop immediately.
Changes the loop's condition.
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help