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

Python में while Loop

while loop किसी काम को तब तक दोहराता रहता है जब तक कुछ सच बना रहता है, जैसे सूप को गर्म होने तक हिलाना। जब condition false हो जाती है, तो loop रुक जाता है।
Syntax
python
while condition:
    # loop body
    update_variable

साधारण While Loop

while loop हर pass से पहले अपनी condition दोबारा जाँचता है और जब तक वह condition True बनी रहती है तब तक अपना body चलाता रहता है; जैसे ही वह False का मूल्यांकन करती है, loop बाहर निकल जाता है और उसके बाद execution आगे बढ़ता है।

उदाहरण: Simple While Loop

python
count = 0
while count < 3:  # loop continues as long as this stays True
    print(count)
    count += 1  # without this, the condition would never become False

घटते (Decrementing) Loops

हर iteration में loop variable से घटाना while loop को नीचे की तरफ़ गिनने देता है -- countdowns, retry limits, या values की घटती range को zero तक process करने के लिए यह एक common pattern है।

उदाहरण: Decrementing Loops

python
countdown = 3
while countdown > 0:
    print(countdown)
    countdown -= 1  # counts down toward zero each iteration

Loop Control के लिए Flags का उपयोग

एक boolean variable को loop की condition के रूप में इस्तेमाल करना -- while running: -- loop body के अंदर कहीं भी code को उस flag को False set करके loop खत्म करने देता है, जो एक fixed numeric condition से ज़्यादा flexible है जब stop point runtime logic पर निर्भर करता है।

उदाहरण: Using Flags for Loop Control

python
running = True
while running:  # loop continues while the flag is True
    print("Running")
    running = False  # setting the flag False ends the loop next check

Lists के साथ While Loop

.pop() के साथ while loop को जोड़ना list को एक बार में एक item खाली करने का common तरीका है, क्योंकि हर iteration में list छोटी होती जाती है और खाली होते ही loop स्वाभाविक रूप से खत्म हो जाता है।

उदाहरण: While Loop with Lists

python
items = [1, 2, 3]
while items:  # loop continues while the list is non-empty
    print(items.pop())  # removes and prints the last item, shrinking the list

गणितीय (Mathematical) Loops

हर pass में loop variable को (एक fixed amount जोड़ने या घटाने के बजाय) गुणा या भाग करना exponential growth या decay produce करता है, जो simulations या binary search जैसे algorithms के लिए उपयोगी है जो बार-बार किसी range को आधा करते रहते हैं।

उदाहरण: Mathematical Loops

python
value = 1
while value < 100:
    print(value)
    value *= 2  # doubles each iteration, growing exponentially
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.