
Python Break, Continue, and Pass Statements with Examples
Python’s loop control statements โ break, continue, pass โ are essential for modifying the flow of loops like for and while. Let’s explore each statement with practical examples.
Statement
The break statement is used to terminate the loop immediately when a specific condition is met.
Example: break in For Loop
python
my_list = [‘Siya’, ‘Tiya’, ‘Software Moji’, ‘Daksh’, ‘Riya’]
for name in my_list:
print(name)
if name == ‘Software Moji’:
print(‘Found the name Software Moji’)
break
print(‘Loop is Terminated’)
Output:
pgsql
Siya
Tiya
Software Moji
Found the name Software Moji
Loop is Terminated
Example: break in While Loop
python
my_list = [‘Siya’, ‘Tiya’, ‘Software Moji’, ‘Daksh’, ‘Riya’]
i = 0
while i < len(my_list):
print(my_list[i])
if my_list[i] == ‘Software Moji’:
print(‘Found the name Software Moji’)
break
i += 1
print(‘After while-loop exit’)
Output:
pgsql
Siya
Tiya
Software Moji
Found the name Software Moji
After while-loop exit
Statement
The continue statement skips the remaining code in the current iteration and moves to the next iteration.
Example: continue in For Loop
python
for i in range(10):
if i == 7:
continue
print(“The Number is:”, i)
Output:
python
The Number is: 0
The Number is: 1
…
The Number is: 6
The Number is: 8
The Number is: 9
Example: continue in While Loop
python
i = 0
while i <= 10:
if i == 7:
i += 1
continue
print(“The Number is:”, i)
i += 1
Output:
python
The Number is: 0
The Number is: 1
…
The Number is: 6
The Number is: 8
…
pass Statement
The pass statement is used as a placeholder for future code. It does nothing when executed.
Example: pass in Function
python
def my_function():
pass
Example: pass in Loop
python
for i in range(5):
if i == 3:
pass
print(i)
๐น Summary
โ
Use break to terminate a loop immediately.
โ
Use continue to skip the current iteration and move to the next one.
โ
Use pass as a placeholder for code you intend to implement later.