Loops and Control Statements (continue, break and pass) in Python (original) (raw)
Last Updated : 04 Jan, 2025
Python supports two types of loops: for loops and while loops. Alongside these loops, Python provides control statements like continue, break, and pass to manage the flow of the loops efficiently. This article will explore these concepts in detail.
Table of Content
for Loops
A for loop in Python is used to iterate over a sequence (such as a list, tuple, string, or range).
Python `
Iterating over a list
a = [1, 2, 3] for i in a: print(i)
`
while Loops
A while loop in Python repeatedly executes a block of code as long as a given condition is True.
Python `
Using while loop
cnt = 0 while cnt < 5: print(cnt) cnt += 1
`
Control Statements in Loops
Control statements modify the loop’s execution flow. Python provides three primary control statements: continue, break, and pass.
break Statement
The break statement is used to exit the loop prematurely when a certain condition is met.
Python `
Using break to exit the loop
for i in range(10): if i == 5: break print(i)
`
**Explanation:
- The loop prints numbers from 0 to 9.
- When i equals 5, the break statement exits the loop.
**continue Statement
The continue statement skips the current iteration and proceeds to the next iteration of the loop.
Python `
Using continue to skip an iteration
for i in range(10): if i % 2 == 0: continue print(i)
`
**Explanation:
- The loop prints odd numbers from 0 to 9.
- When i is even, the continue statement skips the current iteration.
pass Statement
The pass statement is a null operation; it does nothing when executed. It’s useful as a placeholder for code that you plan to write in the future.
Python `
Using pass as a placeholder
for i in range(5):
if i == 3:
pass
print(i)
`
**Explanation:
- The pass statement does nothing and allows the loop to continue executing.
- It is often used as a placeholder for future code.
**Exercise: How to print a list in reverse order (from last to the first item) using while and for-in loops.