Python में break और continue
In this page:
for item in iterable:
if condition:
break # exit loop
if other_condition:
continue # skip to next item
Break Statement
break सबसे नज़दीकी enclosing loop से तुरंत बाहर निकल जाता है, बाकी बची सभी iterations को पूरी तरह skip कर देता है -- यह तब उपयोगी है जब आपको वह मिल गया हो जो आप ढूँढ रहे थे और बाकी जाँचने की कोई ज़रूरत नहीं है।
उदाहरण: The Break Statement
for n in [1, 2, 3, 4]:
if n == 3:
break # exits the loop immediately, 4 is never reached
print(n)
Continue Statement
continue सिर्फ़ मौजूदा iteration के बाकी हिस्से को skip करता है और सीधे loop की अगली जाँच पर चला जाता है, break की तरह पूरे loop को खत्म करने के बजाय -- यह उन cases को filter out करने के लिए काम आता है जिन्हें आप नज़रअंदाज़ करना चाहते हैं, बिना loop body को किसी if के इर्द-गिर्द restructure किए।
उदाहरण: The Continue Statement
for n in [1, 2, 3, 4]:
if n == 2:
continue # skips printing 2, then moves to the next iteration
print(n)
Break के साथ While Loop
break को while True: loop के साथ जोड़ना "जब तक कोई condition पूरी न हो तब तक loop करो" के लिए एक common pattern है, जो exit condition को सिर्फ़ loop के header में नहीं बल्कि body में कहीं भी रखने देता है।
उदाहरण: While Loop with Break
while True: # loop with no condition, relies on break to end
print("Looping once")
break # exits immediately after the first pass
Continue के साथ While Loop
while loop के अंदर continue इस्तेमाल करते समय यह सुनिश्चित करें कि counter update continue line से *पहले* हो -- वरना skip हुई iterations के लिए counter कभी आगे नहीं बढ़ेगा, और loop हमेशा के लिए चलता रहेगा।
उदाहरण: While Loop with Continue
i = 0
while i < 5:
i += 1 # counter updated before continue, so the loop still progresses
if i == 3:
continue # skips the print below only for this iteration
print(i)
Loops में Else Block
loop का वैकल्पिक else block तभी चलता है जब loop बिना कभी break से टकराए अपनी सभी iterations पूरी कर ले -- यह एक कम-जाना-पहचाना feature है जो search loops में उपयोगी है जहाँ आप जानना चाहते हैं कि target असल में मिला या नहीं।
उदाहरण: Else Block in Loops
for n in [1, 2, 3]:
if n == 5:
break
else: # runs only if the loop finished without hitting break
print("Never broke out")
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: