Python में while Loop
In this page:
while condition:
# loop body
update_variable
साधारण While Loop
while loop हर pass से पहले अपनी condition दोबारा जाँचता है और जब तक वह condition True बनी रहती है तब तक अपना body चलाता रहता है; जैसे ही वह False का मूल्यांकन करती है, loop बाहर निकल जाता है और उसके बाद execution आगे बढ़ता है।
उदाहरण: Simple While Loop
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
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
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
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
value = 1
while value < 100:
print(value)
value *= 2 # doubles each iteration, growing exponentially
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: