← Back to Python Course | Chapter 3: Control Flow | Lesson 7 of 10

Python में break और continue

break से आप loop को जल्दी छोड़ सकते हैं, जैसे कोई game जीतने के बाद उससे बाहर निकल जाना। continue सिर्फ़ मौजूदा turn को skip करता है और अगले पर बढ़ जाता है।
Syntax
python
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

python
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

python
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

python
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

python
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

python
for n in [1, 2, 3]:
    if n == 5:
        break
else:  # runs only if the loop finished without hitting break
    print("Never broke out")
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.