Python Loop Control Statements: Break and Continue

Understand Python: LESSON 10 LOOP CONTROL STATEMENTS IN PYTHON Normally, loops run from start to finish. But sometimes, we want to: • Stop a loop early • Skip a particular step • Leave a placeholder for future code Python provides loop control statements for this purpose. ■ What Are Loop Control Statements? Loop control statements change the normal flow of a loop. Python has two main loop control statements: 1. break 2. continue ■ The break Statement break is used to immediately stop a loop, even if the loop condition is still true. Example 1: for i in range(10): if i == 5: break print(i) Our Output would be: 0 1 2 3 4 ➡️ Once i becomes 5, the loop stops completely. ■ The continue Statement continue is used to skip the current iteration and move to the next one. Example 1: for i in range(5): if i == 2: continue print(i) Our Output: 0 1 3 4 ➡️ When i is 2, Python skips printing and continues. ■ When to Use Each: 1. Use break when a goal is reached 2. Use continue to ignore unwanted cases Let's look at a few more examples. ▪︎ Example 1: numbers = [2, 4, 6, 8, 9, 10] for num in numbers: if num % 2 != 0: print("First odd number found:", num) break (Drop the answer to this 👆 in the comment) ▪︎ Example 2: for i in range(1, 11): if i % 2 != 0: continue print(i) ➡️ Prints only even numbers. #python

  • No alternative text description for this image

Learning Python as a beginner doesn’t have to be confusing. I share simple, structured Python lessons and coding tips on my YouTube channel for people starting out in tech. 🎥 Subscribe here: https://youtube.com/@tonybenard7210?si=8R6opV3kZ_HDR242

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories