Syntax:-
With for Loop
for variable in sequence:
statement
else:
statement
With while Loop :-
while condition:
statement
else:
statement
Example with for Loop :-
for i in range(1, 6):
print(i)
else:
print("Loop Completed")
Output:-
1
2
3
4
5
Loop Completed
Because:-
range(1, 6) → 1, 2, 3, 4, 5
Loop की सभी values successfully execute हो गईं। Loop में कोई break नहीं आया, इसलिए loop पूरा होने के बाद else block execute हुआ।
English
The loop completes all its iterations normally. Since no break statement is used, the else block executes after the loop finishes.
else with break :-
अगर loop के अंदर break statement execute हो जाता है, तो else block execute नहीं होता।
Example:-
for i in range(1, 6):
if i == 4:
break
print(i)
else:
print("Loop Completed")
Output:-
1
2
3
Because:-
जब i = 4 हुआ, तब break execute हो गया। break ने loop को बीच में ही समाप्त कर दिया। इसलिए else block नहीं चला।
English
When i becomes 4, the break statement stops the loop. Since the loop did not finish normally, the else block is not executed.
Important Rule :-
Without break -
Loop completes normally
↓
else executes
With break -
break occurs
↓
Loop stops
↓
else does not execute
हिंदी में आसान भाषा में:
👉 Loop पूरा हुआ → else चलेगा
👉 break से loop रुका → else नहीं चलेगा
Example: Number Search :-
# else with loop का सबसे useful example searching है।
numbers = [10, 20, 30, 40, 50]
for n in numbers:
if n == 30:
print("Number Found")
break
else:
print("Number Not Found")
Output:-
Number Found
Explanation:-
List में 30 मिल गया, इसलिए "Number Found" print हुआ और break ने loop को रोक दिया। इसलिए else execute नहीं हुआ।
English
The number 30 is found in the list, so "Number Found" is printed and break stops the loop. Therefore, the else block does not execute.
जब Number नहीं मिले :-
numbers = [10, 20, 40, 50]
for n in numbers:
if n == 30:
print("Number Found")
break
else:
print("Number Not Found")
Output:-
Number Not Found
Because:-
यहाँ 30 list में नहीं है। इसलिए break execute नहीं हुआ और loop पूरी तरह complete हो गया। इसलिए else block execute हुआ।
English
Here, 30 is not present in the list. The break statement is never executed, so the loop completes normally and the else block executes.
else with while Loop :-
else clause को while loop के साथ भी use किया जा सकता है।
Example:-
i = 1
while i <= 5:
print(i)
i += 1
else:
print("Loop Completed")
Output:-
1
2
3
4
5
Loop Completed
Explanation:-
while loop की condition जब False हो गई और loop normally समाप्त हुआ, तब else block execute हुआ।
English
When the while condition became False, the loop finished normally, so the else block was executed.
Use of else with Loops :-
else clause का उपयोग मुख्य रूप से:
- Search में
यह पता लगाने के लिए कि item मिला या नहीं।
- Loop completion check करने में
यह बताने के लिए कि loop successfully complete हुआ।
- break के साथ
यह check करने के लिए कि loop break से रुका या normally complete हुआ।