Using a For Loop with range()
The range() function generates a sequence of numbers. In the following example,range(10) produces numbers from 0 to 9. The variable i automatically takes on each value in the sequence, and the loop prints each number:
Breaking Out of a Loop
By default, a for loop continues until it has gone through the entire sequence. However, if you want to stop the loop early based on a condition (for example, wheni equals 2), you can combine an if statement with the break keyword.
Consider this standard loop without interruption:
i equals 2, modify the code as follows:
i becomes 2, the condition is met and the break statement terminates the loop immediately.
Remember that using break will exit the loop entirely, so any code below the break statement will not be executed for the current iteration.
Skipping Iterations with continue
Sometimes, you may want to skip only the current iteration of a loop instead of terminating it completely. The continue keyword allows you to do just that by skipping the rest of the code inside the loop for that particular iteration and moving on to the next one. In the following example, the iteration is skipped wheni equals 2:
i equal to 2, the continue statement causes Python to skip the print statement for that iteration.
Use continue when you simply want to omit certain iterations without breaking the entire loop. This helps to keep the loop structure intact while filtering out unwanted cases.
Recap
| Concept | Description | Example |
|---|---|---|
| For Loop | Iterates over each element in an iterable. | for i in range(10): |
| Range Function | Generates a sequence of numbers. | range(10) produces 0 to 9 |
| Break Keyword | Exits the loop immediately when a specific condition is met. | if i == 2: break |
| Continue Keyword | Skips the current iteration and proceeds to the next one in the loop sequence. | if i == 2: continue |
Final Thoughts
For loops are essential for iterating over sequences and automating repetitive tasks in Python. By mastering the use ofrange(), break, and continue, you can write more efficient and cleaner code. Start practicing these concepts with hands-on exercises to reinforce your learning and boost your Python programming skills.
Happy coding!