लू

लूप में Python

93 अभ्यास

लूप के बारे में

Python में लूप के दो तरीके हैं। while लूप अनिश्चित (बिना गिनती वाले) इटरेशन के लिए होते हैं और for लूप निश्चित (गिनती वाले) इटरेशन के लिए। break, continue और else कीवर्ड लूप के व्यवहार को अपनी ज़रूरत के हिसाब से बदलने में मदद करते हैं। range() और enumerate() लूप की गिनती और इंडेक्सिंग में मदद करते हैं।

While

while लूप तब तक चलते रहते हैं जब तक loop expression या "टेस्ट" किसी boolean context में True निकलता है, और जैसे ही यह False निकलता है, वे रुक जाते हैं:

# Lists are considered "truthy" in a boolean context if they
# contain one or more values, and "falsy" if they are empty.

>>> placeholders = ["spam", "ham", "eggs", "green_spam", "green_ham", "green_eggs"]

>>> while placeholders:
...     print(placeholders.pop(0))
...
'spam'
'ham'
'eggs'
'green_spam'
'green_ham'
'green_eggs'

For

Python में मूल for loop को for each कहना ज़्यादा सही बैठता है, जो किसी भी इटरेबल ऑब्जेक्ट की वैल्यूओं पर एक-एक करके चलता है और तब रुक जाता है जब next() को कॉल करने पर कोई वैल्यू नहीं लौटती (यानी StopIteration उठती है)।

>>> word_list = ["bird", "chicken", "barrel", "bongo"]

>>> for word in word_list:
...    if word.startswith("b"):
...        print(f"{word.title()} starts with a B.")
...    else:
...        print(f"{word.title()} doesn't start with a B.")
...
'Bird starts with a B.'
'Chicken doesn\'t start with a B.'
'Barrel starts with a B.'
'Bongo starts with a B.'

Sequence Object range()

जब कोई खास iterable नहीं दिया गया हो, तो लूप की गिनती के लिए विशेष range() सीक्वेंस इस्तेमाल किया जाता है। range() को एक int चाहिए जिससे पहले यह सीक्वेंस stop कर दे, और यह चाहें तो start और step पैरामीटर भी ले सकता है। अगर कोई start संख्या नहीं दी गई हो, तो सीक्वेंस 0 से शुरू होता है। range() ऑब्जेक्ट लेज़ी होते हैं (वैल्यूएँ माँगने पर ही बनती हैं), सामान्य सीक्वेंस ऑपरेशन का पूरा साथ देते हैं, और सीक्वेंस कितना ही लंबा क्यों न हो, वे एक तय जगह ही मेमोरी लेते हैं। दिलचस्प बात यह है कि range() एक इटरेटर नहीं है, और इसका इस्तेमाल ऐसे कई मौकों पर किया जा सकता है जहाँ लूप नहीं चल रहा हो पर संख्याओं का सीक्वेंस चाहिए हो।

# Here we use range to produce some numbers, rather than creating a list of them in memory.
# The values will start with 1 and stop *before* 7.

>>> for number in range(1, 7):
...    if number % 2 == 0:
...       print(f"{number} is even.")
...    else:
...       print(f"{number} is odd.")
'1 is odd.'
'2 is even.'
'3 is odd.'
'4 is even.'
'5 is odd.'
'6 is even.'

# range() can also take a *step* parameter.
# Here we use range to produce only the "odd" numbers, starting with 3 and stopping *before* 15.

>>> for number in range(3, 15, 2):
...    if number % 2 == 0:
...       print(f"{number} is even.")
...    else:
...       print(f"{number} is odd.")
...
'3 is odd.'
'5 is odd.'
'7 is odd.'
'9 is odd.'
'11 is odd.'
'13 is odd.'

enumerate() के साथ वैल्यू और इंडेक्स

अगर वैल्यू और इंडेक्स दोनों चाहिए हों, तो बिल्ट-इन enumerate(<iterable>) (index, value) जोड़ों पर एक iterator लौटाता है:

>>> word_list = ["bird", "chicken", "barrel", "apple"]

# *index* and *word* are the loop variables.
# Loop variables can be any valid python name.

>>> for index, word in enumerate(word_list):
...    if word.startswith("b"):
...        print(f"{word.title()} (at index {index}) starts with a B.")
...    else:
...        print(f"{word.title()} (at index {index}) doesn't start with a B.")
...
'Bird (at index 0) starts with a B.'
'Chicken (at index 1) doesn\'t start with a B.'
'Barrel (at index 2) starts with a B.'
'Apple (at index 3) doesn\'t start with a B.'


# The same method can be used as a "lookup" for pairing items between two lists.
# Of course, if the lengths or indexes don't line up, this doesn't work.

>>> word_list = ["cat", "chicken", "barrel", "apple", "spinach"]
>>> category_list = ["mammal", "bird", "thing", "fruit", "vegetable"]

>>> for index, word in enumerate(word_list):
...    print(f"{word.title()} is in category: {category_list[index]}.")
...
'Cat is in category: mammal.'
'Chicken is in category: bird.'
'Barrel is in category: thing.'
'Apple is in category: fruit.'
'Spinach is in category: vegetable.'

enumerate(<iterable>) फंक्शन में start देकर इंडेक्स की गिनती किसी और संख्या से भी शुरू की जा सकती है:

# Here, the index count will start at 1.
>>> for position, word in enumerate(word_list, start=1):
...    if word.startswith("b"):
...        print(f"{word.title()} (at position {position}) starts with a B.")
...    else:
...        print(f"{word.title()} (at position {position}) doesn't start with a B.")
...
'Bird (at position 1) starts with a B.'
'Chicken (at position 2) doesn\'t start with a B.'
'Barrel (at position 3) starts with a B.'
'Apple (at position 4) doesn\'t start with a B.'

लूप का व्यवहार बदलना

continue कीवर्ड का इस्तेमाल करके सीधे अगले इटरेशन पर पहुँचा जा सकता है:

>>> word_list = ["bird", "chicken", "barrel", "bongo", "sliver", "apple", "bear"]
...
... # This will skip *bird*, at index 0
... for index, word in enumerate(word_list):
...     if index == 0:
...         continue
...     if word.startswith("b"):
...         print(f"{word.title()} (at index {index}) starts with a b.")
...
'Barrel (at index 2) starts with a b.'
'Bongo (at index 3) starts with a b.'
'Bear (at index 6) starts with a b.'

break कीवर्ड (जैसा कई C से जुड़ी भाषाओं में होता है) इटरेशन रोकने और सबसे अंदर वाले loop से "बाहर निकलने" के लिए इस्तेमाल किया जा सकता है:

>>>  word_list = ["bird", "chicken", "barrel", "bongo", "sliver", "apple"]

>>> for index, word in enumerate(word_list):
...    if word.startswith("b"):
...        print(f"{word.title()} (at index {index}) starts with a B.")
...    elif word == "sliver":
...        break
...    else:
...        print(f"{word.title()} doesn't start with a B.")
... print("loop broken.")
...
'Bird (at index 0) starts with a B.'
'Chicken doesn\'t start with a B.'
'Barrel (at index 2) starts with a B.'
'Bongo (at index 3) starts with a B.'
'loop broken.'

लूप का else क्लॉज़ सिर्फ Python में मिलता है और इसका इस्तेमाल तब "समेटने" या "खत्म करने" वाले कामों के लिए किया जा सकता है जब इटरेशन पूरा हो चुका हो। अगर इटरेशन break से रुका हो, तो else कीवर्ड के बाद वाले स्टेटमेंट नहीं चलते:

>>> word_list = ["bird", "chicken", "barrel", "bongo", "sliver", "apple"]

# Using enumerate to get both an index and a value.

>>> for index, word in enumerate(word_list):
...    word = word.title()
...    if word.startswith("B"):
...        print(f"{word} (at index {index}) starts with a B.")
...
... # This executes once *StopIteration* is raised and 
... # There are no more items to iterate through.
... # Note the indentation, which lines up with the for keyword.
... else:
...    print(f"Found the above b-words, out of {len(word_list)} words in the word list.")
...
'Bird (at index 0) starts with a B.'
'Barrel (at index 2) starts with a B.'
'Bongo (at index 3) starts with a B.'
'Found the above b-words, out of 6 words in the word list.'


# Terminating a loop via *break* will bypass the loop *else* clause

>>> for index, word in enumerate(word_list):
...    word = word.title()
...    if word.startswith("B"):
...       print(f"{word} (at index {index}) starts with a B.")
...    if word.startswith("S"):
...        print("Found an S, stopping iteration.")
...        break

... # This statement does not run, because a *break* was triggered.
... else:
...    print(f"Found the above b-words, out of {len(word_list)} words in the word list.")
...
'Bird (at index 0) starts with a B.'
'Barrel (at index 2) starts with a B.'
'Bongo (at index 3) starts with a B.'
'Found an S, stopping iteration.'
GitHub के ज़रिए संपादित करें यह लिंक नई विंडो या टैब में खुलता है।

लूप सीखिए

अभ्यास लॉक है

लूप पर अभ्यास करने के लिए 6 और अभ्यास अनलॉक कीजिए