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

Python में for Loop

for loop चीज़ों के एक समूह में से एक-एक करके गुज़रता है, जैसे लाइन में खड़े हर बच्चे को एक sticker देना। आप steps एक बार लिखते हैं और Python उन्हें हर item के लिए दोहराता है।
Syntax
python
for item in iterable:
    # loop body

for i in range(start, stop, step):
    # loop body

Lists पर Iterate करना

for loop किसी sequence -- list, string, tuple, या किसी अन्य iterable -- के हर item में से अपने-आप एक-एक करके गुज़रता है, बिना आपको while loop की तरह खुद index counter manage करने की ज़रूरत के।

उदाहरण: Iterating over Lists

python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:  # fruit takes each list item in turn
    print(fruit)

Range के साथ Iterate करना

range() हर बार मांग पर numbers की एक sequence generate करता है, उन्हें एक साथ memory में store करने के बजाय, यही वजह है कि for i in range(10): किसी block को एक fixed संख्या में चलाने का standard तरीका है।

उदाहरण: Iterating with Range

python
for i in range(5):
    print(i)

Strings में Loop करना

for char in text: से किसी string पर loop करना उसके हर character को क्रम से visit करता है, जो vowels गिनने, text को manually reverse करने, या यह verify करने जैसे कामों की बुनियाद है कि हर character किसी rule को पूरा करता है या नहीं।

उदाहरण: Looping through Strings

python
for char in "cat":
    print(char)

Dictionaries पर Iterate करना

किसी dictionary पर सीधे iterate करने से default रूप से उसकी keys पर loop होता है; अगर आपको हर pass में key और उसकी corresponding value दोनों चाहिए तो .items() इस्तेमाल करें, या सिर्फ़ values चाहिए तो .values()

उदाहरण: Iterating over Dictionaries

python
user = {"name": "Alex", "age": 30}
for key, value in user.items():  # .items() yields both key and value each pass
    print(key, value)

Nested For Loops

एक for loop को दूसरे for loop के अंदर रखने से outer loop की हर single iteration के लिए inner loop पूरा चलता है -- यह grid या lists की list जैसे two-dimensional structures पर काम करने की standard technique है।

उदाहरण: Nested For Loops

python
for i in range(2):  # outer loop
    for j in range(2):  # inner loop runs fully for each outer iteration
        print(i, j)
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.