Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

⚡ Python Break, Continue and Else in Loops

Python Break Continue Else in Loops - Complete Guide

Master loop control with break, continue, and else — essential tools for writing efficient Python programs.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
📑 On this page:
  • Welcome: Why Loop Control Matters
  • The break Statement
  • The continue Statement
  • The else Clause in Loops
  • Break vs Continue vs Else
  • Real-World Examples
  • Common Mistakes
  • Try It Yourself
  • Quick Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
📚 What You'll Learn Here
  • The break statement — how to exit a loop completely
  • The continue statement — how to skip an iteration
  • The else clause — what happens when a loop completes normally
  • When to use each — choosing the right control statement
  • Real-world examples — practical applications
  • Common mistakes — and how to avoid them

Welcome: Why Loop Control Matters

📖 Think of it this way: Imagine you're searching for a book in a library. You look at each shelf one by one. When you find the book, you stop searching — you don't keep looking at the remaining shelves. That's what break does. If you find a book that's damaged, you skip it and move to the next one — that's continue. And if you've checked every single shelf and didn't find the book, you might go to the front desk — that's the else clause.

Python provides three powerful tools to control loops: break, continue, and else. Each serves a different purpose and helps you write cleaner, more efficient code. Whether you're searching for data, filtering items, or handling errors, these statements are essential for every Python programmer.

💡 Key insight: break and continue work in both for and while loops. The else clause is a unique Python feature that runs only when the loop completes without a break.

The break Statement

1

Exiting a Loop Completely

The break statement immediately exits the loop, regardless of the loop condition.

# Example 1: Stop when you find what you're looking for
numbers = [1, 3, 5, 7, 8, 9, 11]
print("Searching for even number:")
for num in numbers:
    print(f"Checking {num}...")
    if num % 2 == 0:
        print(f"Found an even number: {num}")
        break
# Output:
# Checking 1...
# Checking 3...
# Checking 5...
# Checking 7...
# Checking 8...
# Found an even number: 8

# Example 2: Stop after a certain condition
count = 0
while True:
    print(f"Count: {count}")
    count += 1
    if count == 5:
        break
# Output: Count: 0, 1, 2, 3, 4

When to use break:

  • When you've found what you're looking for
  • When you need to stop a loop early based on a condition
  • When you want to exit an infinite loop
  • When you're processing data and a condition is met

✅ Quick Check: What does break do? (Answer: It exits the loop completely)

The continue Statement

2

Skipping an Iteration

The continue statement skips the rest of the current iteration and moves to the next one.

# Example 1: Skip even numbers
for i in range(10):
    if i % 2 == 0:
        continue
    print(i)
# Output: 1 3 5 7 9

# Example 2: Skip numbers divisible by 3
for i in range(1, 11):
    if i % 3 == 0:
        continue
    print(i)
# Output: 1 2 4 5 7 8 10

# Example 3: Skip invalid input
while True:
    user_input = input("Enter a number (or 'exit'): ")
    if user_input == "exit":
        break
    if not user_input.isdigit():
        print("That's not a number! Try again.")
        continue
    print(f"You entered: {int(user_input)}")

When to use continue:

  • When you want to skip certain items in a loop
  • When you need to filter out invalid data
  • When you want to avoid nested conditions
  • When you want to keep the loop running but skip specific cases

✅ Quick Check: What does continue do? (Answer: It skips the rest of the current iteration and moves to the next one)

The else Clause in Loops

3

What Happens When a Loop Completes Normally

The else clause runs only when the loop completes without hitting a break statement.

# Example 1: For loop with else
print("Searching for 5:")
for i in range(1, 4):
    if i == 5:
        print("Found 5!")
        break
else:
    print("5 not found!")
# Output: 5 not found!

# Example 2: While loop with else
count = 0
while count < 3:
    print(f"Count: {count}")
    count += 1
else:
    print("Loop completed normally!")
# Output:
# Count: 0
# Count: 1
# Count: 2
# Loop completed normally!

# Example 3: Finding a prime number
num = 17
for i in range(2, int(num ** 0.5) + 1):
    if num % i == 0:
        print(f"{num} is not prime")
        break
else:
    print(f"{num} is prime")
# Output: 17 is prime

When to use else:

  • When you need to check if a loop completed without a break
  • When you're searching and want to know if something was found
  • When you need to handle "not found" cases cleanly
  • When you want to avoid using flag variables

✅ Quick Check: When does the else clause in a loop run? (Answer: When the loop completes without a break)

Break vs Continue vs Else

4

Comparing the Three Statements

Here's a quick comparison to help you remember when to use each:

break

  • Exits the loop
  • Stops all iterations
  • Used when you found what you want
  • Used in infinite loops

continue

  • Skips current iteration
  • Continues to next iteration
  • Used to skip certain items
  • Used for filtering

else

  • Runs after loop ends
  • Only if no break occurred
  • Used for "not found" cases
  • Used for completion checks
# Visual comparison
print("--- BREAK ---")
for i in range(5):
    if i == 3:
        break
    print(i)
# Output: 0 1 2

print("--- CONTINUE ---")
for i in range(5):
    if i == 3:
        continue
    print(i)
# Output: 0 1 2 4

print("--- ELSE ---")
for i in range(3):
    print(i)
else:
    print("Loop completed!")
# Output: 0 1 2 Loop completed!

✅ Quick Check: Which statement exits the loop completely? (Answer: break)

Real-World Examples

5

Practical Applications

💡 Example 1: Password Validation

# Keep asking until user enters a valid password
while True:
    password = input("Enter password (min 8 chars): ")
    if len(password) >= 8:
        print("Password accepted!")
        break
    else:
        print("Password too short. Try again.")

💡 Example 2: Processing Student Scores

# Process scores and find first failing student
scores = [85, 92, 78, 55, 90, 88]
found_failing = False

for score in scores:
    if score < 60:
        print(f"Failing student found: {score}")
        found_failing = True
        break
else:
    print("All students passed!")

if found_failing:
    print("A student needs extra help.")

💡 Example 3: Menu System with Input Validation

# Menu system that handles invalid input
while True:
    print("\n1. View Data")
    print("2. Add Data")
    print("3. Delete Data")
    print("4. Exit")
    
    try:
        choice = int(input("Choose: "))
    except ValueError:
        print("Please enter a valid number!")
        continue
    
    if choice == 4:
        print("Goodbye!")
        break
    elif choice == 1:
        print("Data displayed.")
    elif choice == 2:
        print("Data added.")
    elif choice == 3:
        print("Data deleted.")
    else:
        print("Invalid choice. Try again.")

✅ Quick Check: In the menu example, what happens if the user enters "exit"? (Answer: The break statement exits the loop)

Common Mistakes to Avoid

6

Watch Out For These!

❌ Mistake 1: Using break in the Wrong Place

If you put break outside a loop, you'll get a SyntaxError:

# WRONG
for i in range(5):
    print(i)
break  # SyntaxError! 'break' outside loop

# CORRECT
for i in range(5):
    if i == 3:
        break
    print(i)

❌ Mistake 2: Confusing break and continue

They're different! break exits the loop; continue skips the current iteration:

# Wrong expectation
for i in range(5):
    if i == 2:
        continue
    print(i)
# Output: 0 1 3 4 (skips 2, doesn't stop)

# Right expectation
for i in range(5):
    if i == 2:
        break
    print(i)
# Output: 0 1 (stops at 2)

❌ Mistake 3: Not Understanding else in Loops

The else runs only if the loop completes without a break:

# WRONG assumption
for i in range(3):
    if i == 1:
        break
else:
    print("Loop ended")
# Output: (nothing) — else doesn't run because break occurred

# CORRECT understanding
for i in range(3):
    print(i)
else:
    print("Loop ended")
# Output: 0 1 2 Loop ended

✅ Quick Check: What happens to the else block when a break occurs? (Answer: The else block doesn't run)

Try It Yourself!

Experiment with break, continue, and else directly in your browser. Modify the code and see the results in real time.

Loading Pyodide... 0%
Python Code Editor
========================================
BREAK, CONTINUE, ELSE - PRACTICE
========================================

1. BREAK EXAMPLE
0 1 2 (loop stopped at 3)

2. CONTINUE EXAMPLE
0 1 2 4 (skipped 3)

3. ELSE EXAMPLE
0 1 2 (loop completed)

4. BREAK + ELSE
0 1 2

✅ Explore loop control!
🏆

🎉 You've Mastered Loop Control Statements!

You understand break, continue, and else in loops. These are essential tools for writing efficient, clean Python code!

Quick Quiz – Test Your Knowledge

Let's see what you've learned about loop control statements:

1. What does the break statement do?
2. What does the continue statement do?
3. When does the else clause in a loop run?
4. Which statement is used in an infinite loop to exit it?
5. What is the output of: for i in range(5): if i == 2: continue; print(i)?

Frequently Asked Questions

🤔 Can I use break and continue together? ▼

Yes! You can use both break and continue in the same loop. continue skips the current iteration, and break exits the loop entirely. They serve different purposes and can be used together.

🔧 Does else work in while loops too? ▼

Yes! The else clause works in both for and while loops. It runs when the loop condition becomes False (for while) or when the sequence is exhausted (for for) — as long as no break occurred.

📐 What's the difference between pass and continue? ▼

pass does nothing — it's a placeholder. continue skips the rest of the current iteration and moves to the next one. pass is used when you need a statement syntactically but don't want to execute anything.

📊 Can I break out of multiple nested loops? ▼

The break statement only exits the innermost loop. To break out of multiple nested loops, you can use a flag variable, wrap the loops in a function and use return, or use a for-else construct with a flag.

⚡ Is using else in loops considered Pythonic? ▼

Yes! The else clause in loops is a Python-specific feature and is considered Pythonic. It's a clean way to handle "not found" cases and avoids using flag variables. However, some developers find it confusing, so use it when it makes your code clearer.

🎯 What's the best practice for using these statements? ▼

Use break to exit loops early when you've found what you need. Use continue to skip invalid or unwanted items. Use else to handle cases where the loop completes without a break. Keep your code simple and avoid using break and continue excessively.

📚 Where to Go From Here

Now that you've mastered break, continue, and else in loops, here are the next topics to explore:

🔄 For vs While

Understand the differences between for and while loops.

Learn More →

📝 All Loops Assignments

Practice all loop concepts with hands-on assignments.

Practice →

🔄 While Loop

Review the basics of while loops.

Review →
📖 Interview & FAQ Resources
  • Python Syntax & Variables Interview Questions
  • SQL - Displaying Data from Multiple Tables FAQ
  • Python Data Types Interview Questions
Previous: Infinite For Loop Next: For vs While →