In the previous lessons, you learned how Python uses for loops and while loops to repeat a block of code. You also learned how the break statement immediately terminates a loop and how the continue statement skips the current iteration.
Python provides another useful feature that is unique compared to many other programming languages—the loop else statement.
Many beginners are surprised to learn that the else keyword is not limited to if statements. In Python, an else block can also be attached to both for loops and while loops.
The else block executes only when the loop finishes normally. If the loop is terminated using a break statement, the else block does not execute.
This feature is particularly useful in search operations, validation programs, prime number checking, and situations where you want to perform an action only after a loop completes successfully.
After completing this lesson, you will be able to:
else statement.else clause with for loops.else clause with while loops.break statement affects loop else.if...else and loop else.else.else Statement?The Python loop else statement is an optional block that can be used with both for loops and while loops.
The else block executes only if the loop finishes all of its iterations normally.
If the loop exits because of a break statement, the else block is skipped.
This behavior makes the loop else statement very useful for search operations and validation tasks.
else Statement?Consider a program that searches for a student’s roll number in a list.
If the roll number is found, the loop stops immediately using the break statement.
But if the entire list is searched and the roll number is not found, the program should display a message such as “Student Not Found.”
Without a loop else statement, you would need an additional variable to determine whether the search was successful.
The loop else statement eliminates this extra work by automatically executing only when the loop completes normally.
for...elsefor variable in sequence:
statements
else:
statements
The else block executes after the for loop finishes all iterations without encountering a break.
while...elsewhile condition:
statements
else:
statements
The else block executes only when the while loop ends because its condition becomes false.
else with a for LoopLet’s look at a simple example.
for number in range(1, 6):
print(number)
else:
print("Loop Completed Successfully")
Output
1
2
3
4
5
Loop Completed Successfully
The else block executes because the loop finishes normally.
else with a while LoopThe else clause works the same way with a while loop.
count = 1
while count <= 5:
print(count)
count += 1
else:
print("Loop Completed Successfully")
Output
1
2
3
4
5
Loop Completed Successfully
Since the condition eventually becomes false, the else block executes.
break Statement Affects Loop elseThe most important rule is:
If a loop ends because of a break statement, the else block is skipped.
for number in range(1, 6):
if number == 3:
break
print(number)
else:
print("Loop Completed")
Output
1
2
The message "Loop Completed" is not printed because the loop terminates using break.
Consider the following program.
for letter in "Python":
print(letter)
else:
print("Finished Processing")
Execution Steps
else block.Output
P
y
t
h
o
n
Finished Processing
if...else and Loop elseif...else |
Loop else |
|---|---|
| Executes based on a condition. | Executes after a loop finishes normally. |
| Works with conditional statements. | Works with for and while loops. |
| Only one block executes. | The loop executes first, then the else block if no break occurs. |
| Independent of loops. | Depends on how the loop terminates. |
else?The loop else statement is useful in situations such as:
In this section, you learned what the Python loop else statement is and how it works with both for and while loops. You explored its syntax, learned why it is useful, understood how the break statement affects the else block, compared loop else with if...else, and followed the execution flow step by step. In the next section, you will learn how to use loop else in search programs, combine it with the break statement, work with nested loops, and avoid common beginner mistakes.
In the previous section, you learned what the Python loop else statement is and how it works with both for and while loops. In this section, you will learn how to use the loop else statement in search programs, understand how the break statement affects it, use it with nested loops, and avoid common beginner mistakes.
for...else in Search ProgramsThe for...else statement is commonly used when searching for an item in a collection.
If the item is found, the loop stops using break. If the loop finishes without finding the item, the else block executes.
numbers = [12, 25, 37, 48, 59]
search = 48
for number in numbers:
if number == search:
print("Number Found")
break
else:
print("Number Not Found")
Output
Number Found
The else block is skipped because the loop terminates using the break statement.
numbers = [12, 25, 37, 48, 59]
search = 100
for number in numbers:
if number == search:
print("Number Found")
break
else:
print("Number Not Found")
Output
Number Not Found
Since the loop finishes normally, the else block executes.
while...elseThe else clause also works with while loops.
count = 1
while count <= 3:
print(count)
count += 1
else:
print("Loop Finished")
Output
1
2
3
Loop Finished
The loop ends because the condition becomes false, so the else block executes.
break with while...elseIf a while loop is terminated using break, the else block does not execute.
count = 1
while count <= 5:
if count == 3:
break
print(count)
count += 1
else:
print("Loop Finished")
Output
1
2
The message "Loop Finished" is not displayed because the loop exits using break.
else Without Using breakYou do not have to use the break statement with a loop else. The else block executes automatically when the loop finishes normally.
for letter in "Python":
print(letter)
else:
print("All Characters Processed")
Output
P
y
t
h
o
n
All Characters Processed
else with Nested LoopsThe else clause can also be used with nested loops. Each loop may have its own else block.
for row in range(1, 3):
for column in range(1, 4):
print(row, column)
else:
print("Inner Loop Finished")
else:
print("Outer Loop Finished")
Output
1 1
1 2
1 3
Inner Loop Finished
2 1
2 2
2 3
Inner Loop Finished
Outer Loop Finished
Each else block belongs to the loop immediately before it.
Consider the following program.
numbers = [5, 10, 15]
for number in numbers:
if number == 20:
break
print(number)
else:
print("Search Completed")
Execution Steps
break statement executes, the else block runs.Output
5
10
15
Search Completed
else Block Executes Only When the Loop Condition Is FalseThe else block executes whenever the loop finishes normally, regardless of why the condition became false.
break Skips the else BlockIf a loop exits using break, Python does not execute the else block.
The else statement must be aligned with the corresponding for or while statement.
else with if...elseRemember that the loop else statement depends on how the loop ends, not on a Boolean condition.
else UnnecessarilyIf an else block does not improve readability or solve a specific problem, it may not be needed.
else mainly for search and validation programs.else block short and meaningful.break only when early loop termination is required.else is not immediately obvious.else block with its loop.In this section, you learned how to use the Python loop else statement with both for and while loops in search and validation programs. You explored how the break statement affects the else block, learned that loop else can be used without break, and saw how it works with nested loops. You also reviewed common beginner mistakes and coding best practices. In the next section, you will build practical programs such as number search, prime number checking, password verification, login attempts, student search, and menu-driven applications using the loop else statement.
The Python loop else statement is especially useful in programs where you need to search for data, validate user input, or determine whether a loop completed successfully. Instead of using additional variables to track whether an item was found, the else block automatically executes if the loop finishes without encountering a break statement.
In this section, you will build practical programs using the loop else statement with both for and while loops.
else StatementThis program searches for a number in a list.
numbers = [15, 25, 35, 45, 55]
search = 35
for number in numbers:
if number == search:
print("Number Found")
break
else:
print("Number Not Found")
Output
Number Found
The else block is skipped because the required number is found.
The loop else statement is commonly used when checking whether a number is prime.
number = 17
for i in range(2, number):
if number % i == 0:
print("Not a Prime Number")
break
else:
print("Prime Number")
Output
Prime Number
If no divisor is found, the loop completes normally and the else block executes.
The following program allows three password attempts.
correct_password = "python123"
for attempt in range(3):
password = input("Enter Password: ")
if password == correct_password:
print("Login Successful")
break
else:
print("Account Locked")
Sample Output
Enter Password: admin
Enter Password: hello
Enter Password: test123
Account Locked
The else block executes because all attempts are used without a successful login.
while...elseThe same logic can also be implemented using a while loop.
attempt = 1
while attempt <= 3:
password = input("Enter Password: ")
if password == "python123":
print("Login Successful")
break
attempt += 1
else:
print("Maximum Attempts Reached")
Sample Output
Enter Password: admin
Enter Password: test
Enter Password: guest
Maximum Attempts Reached
This program searches for a student's name.
students = ["Rahul", "Amit", "Neha", "Riya"]
search = "Neha"
for student in students:
if student == search:
print("Student Found")
break
else:
print("Student Not Found")
Output
Student Found
The following program repeatedly displays a menu until the user chooses the Exit option.
while True:
print("1. Start")
print("2. Help")
print("3. Exit")
choice = int(input("Enter Choice: "))
if choice == 3:
print("Exiting Program")
break
else:
print("Program Finished")
Sample Output
1. Start
2. Help
3. Exit
Enter Choice: 3
Exiting Program
The else block never executes because the loop always ends using break.
This program searches for the first even number in a list.
numbers = [1, 3, 5, 8, 9]
for number in numbers:
if number % 2 == 0:
print("Even Number Found:", number)
break
else:
print("No Even Number Found")
Output
Even Number Found: 8
The following program checks whether a list contains duplicate values.
numbers = [2, 4, 6, 8]
for i in range(len(numbers)):
for j in range(i + 1, len(numbers)):
if numbers[i] == numbers[j]:
print("Duplicate Found")
break
else:
continue
break
else:
print("No Duplicates Found")
Output
No Duplicates Found
Consider the following program.
numbers = [10, 20, 30]
for number in numbers:
if number == 40:
break
print(number)
else:
print("Search Finished")
Execution Steps
break statement executes.else block executes.Output
10
20
30
Search Finished
else for Search OperationsThe loop else statement makes search programs simpler and easier to understand.
break Only When NecessaryTerminate a loop early only when the required result has been found.
else Block ShortThe else block should contain only the logic that should run after successful loop completion.
Variable names such as student, search, and attempt improve readability.
Always test programs where the loop finishes normally and where it exits using break.
In this section, you applied the Python loop else statement to practical programming problems such as number searching, prime number checking, password verification, login attempts, student searching, menu-driven programs, finding even numbers, and checking duplicate values. You also learned coding best practices and followed the execution flow of programs that use the loop else statement. In the final section, you will review the complete lesson through a summary, key takeaways, frequently asked questions, coding exercises, interview questions, a mini project, and a preview of the next lesson on Python Functions.
In this lesson, you learned how the Python loop else statement works with both for loops and while loops. Unlike the else statement used with if conditions, the loop else block executes only when a loop finishes normally without encountering a break statement.
You explored the syntax of for...else and while...else, understood how the break statement affects loop execution, and learned how the loop else statement simplifies search and validation programs. Through practical examples such as number searching, prime number checking, password verification, login attempts, and student search programs, you saw how the loop else statement can make Python programs cleaner and easier to understand.
Although the loop else statement is not used as frequently as other Python features, it is a powerful tool for writing elegant search and validation logic.
else statement can be used with both for and while loops.else block executes only if the loop finishes normally.break statement, the else block is skipped.else statement is useful for search and validation programs.else block.else block belongs to the loop, not to an if statement.else statement?The loop else statement is an optional block that executes after a for or while loop finishes normally.
else block execute?It executes only if the loop completes all of its iterations without encountering a break statement.
else block execute after a break statement?No. If the loop exits because of break, the else block is skipped.
else statement be used with both for and while loops?Yes. Python supports the else clause with both loop types.
if...else and loop else?The if...else statement depends on a Boolean condition, whereas the loop else statement depends on how the loop terminates.
else statement required?No. It is optional and should be used only when it improves the clarity of the program.
else blocks?Yes. Each loop can have its own associated else block.
else statement commonly used?It is commonly used in search operations, prime number checking, validation programs, and algorithms that need to detect whether a loop completed without interruption.
for...else.else statement.while...else program that counts from 1 to 10.break statement on the loop else block.else statement?else block execute?break statement affect the loop else block?else statement be used with both for and while loops?if...else and loop else?else statement.else blocks?else statement useful in search algorithms?Create a Python program that searches for a student's roll number using the for...else statement.
Your program should:
for loop.break.else block.Enter Roll Number: 105
Student Not Found
Search Completed
Congratulations! You have successfully completed the Python Loops section. You now understand for loops, while loops, nested loops, loop control statements, and the loop else statement. These concepts provide a strong foundation for writing efficient programs that repeat tasks, process collections, and control program flow.
In the next lesson, you will begin learning Python Functions. You will discover how to create reusable blocks of code, define functions using the def keyword, pass arguments, return values, understand variable scope, and organize programs into modular, reusable components.