Python break, continue, and pass Explained for Beginners (With Simple Examples)
Python break, continue, and pass Explained for Beginners (With Simple Examples)
Introduction
In the previous post, we learned about Python Dictionary. Now it's time to understand three important control statements used inside loops:
- break
- continue
- pass
These statements help you control how loops behave in Python.
---1️⃣ What is break in Python?
The break statement is used to immediately stop a loop. When Python encounters break, it exits the loop completely.
for i in range(1, 6):
if i == 4:
break
print(i)
When Should You Use break?
- When a condition is met and no further looping is needed
- When searching for something in a list
- When you want to stop early
2️⃣ What is continue in Python?
The continue statement skips the current iteration and moves to the next iteration of the loop.
for i in range(1, 6):
if i == 4:
continue
print(i)
When Should You Use continue?
- When you want to skip specific values
- When some condition should not execute remaining code
3️⃣ What is pass in Python?
The pass statement does nothing. It is used as a placeholder when code is required syntactically, but you do not want to write logic yet.
for i in range(5):
pass
Using pass in Conditions
if 10 > 5:
pass
This will not give an error even though no code is written.
---Difference Between break, continue, and pass
- break → Stops the loop completely
- continue → Skips current iteration
- pass → Does nothing (placeholder)
Real Life Example
numbers = [10, 20, 30, 40, 50]
for num in numbers:
if num == 40:
break
print(num)
The loop stops when number becomes 40.
---What You Learned in This Post
- How break works
- How continue works
- What pass does
- When to use each statement
What’s Next?
Now that you understand loop control statements, the next step is to learn more advanced loop concepts.
Next Post: Python Nested Loops Explained for Beginners
---👋 About the Author
Ayush Gupta
MSc AI/ML Student | Machine Learning & Python Enthusiast
📧 Email:
aygupta9898@gmail.com
Thank you, I really love how you break it down. As a beginner it really helps
ReplyDelete