Lecture
Using break to Stop Loops
The break keyword immediately terminates a loop and proceeds to execute the code that follows the loop.
It is typically used within a loop when a specific condition is met, and further iteration is unnecessary.
Example of Using the break Statement
Stopping a loop using break
# Print numbers from 1 to 10, but stop the loop at 5 for i in range(1, 11): # When i equals 5 if i == 5: # Exit the loop break # Print i print(i)
Output
1 2 3 4
In the code above, the loop for i in range(1, 11): iterates through numbers from 1 to 10, but when i equals 5, it encounters break and the loop terminates.
Lessons in this chapter · What are Conditional Statements and Loops?
- 1. The Crossroads of Logical Flow, Conditional Statements
- 2. Using Comparison Operators in Conditional Statements
- 3. Conditions within Conditions, Nested Conditionals
- 4. Combining Conditions for More Powerful Decisions
- 5. Filling in Gaps with the pass Keyword
- 6. Fill-in-the-blank quiz
- 7. Using Loops to Execute Code Multiple Times
- 8. Repeating a Specific Number of Times with a for Loop
- 9. Controlling Loops with the while Statement
- 10. Loop within a Loop, Nested Loops
- 11. Using break to Stop Loops
- 12. Skip Iteration with continue
- 13. Multiple-choice quiz
- 14. Coding Quiz - Python Temperature Converter
Quiz
0 / 1
What is the most appropriate word to fill in the blank regarding the 'break' keyword?
The break statement the loop.
continues
exits
pauses
skips to the next iteration
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help