Nested Loops :-
Nested Loop Python में ऐसा Loop Structure (लूप संरचना) है जिसमें एक loop के अंदर दूसरा loop लिखा जाता है। इसमें Outer Loop (बाहरी लूप) और Inner Loop (आंतरिक लूप) होते हैं।
जब outer loop की एक iteration execute होती है, तो उसके अंदर का inner loop पूरी तरह execute होता है। इसका उपयोग patterns, tables, matrices और 2D data जैसे कार्यों में किया जाता है।
Python में Nested Loop के अंदर लिखे statements को Indentation (रिक्त स्थान) देना आवश्यक होता है। सामान्यतः प्रत्येक level के लिए 4 spaces का indentation प्रयोग किया जाता है।
English
A Nested Loop is a loop structure in Python in which one loop is written inside another loop. It consists of an Outer Loop and an Inner Loop.
When one iteration of the outer loop is executed, the inner loop executes completely. Nested loops are commonly used for patterns, tables, matrices, and 2D data.
In Python, proper Indentation (spaces) is required for statements inside nested loops. Generally, 4 spaces are used for each level of indentation.
Syntax:-
for variable1 in sequence:
for variable2 in sequence:
statement
Example:
for i in range(1, 4):
for j in range(1, 4):
print(i, j)
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Because:
पहले outer loop में i = 1 होता है। इसके लिए inner loop j की सभी values पर चलता है:
1 1
1 2
1 3
फिर i = 2 होता है और inner loop फिर से पूरा execute होता है:
2 1
2 2
2 3
अंत में i = 3 के लिए:
3 1
3 2
3 3
English
First, the outer loop takes i = 1. The inner loop then runs through all values of j:
1 1
1 2
1 3
Then i = 2, and the inner loop executes completely again:
2 1
2 2
2 3
Finally, the inner loop executes for i = 3:
3 1
3 2
3 3
इस उदाहरण में outer loop 3 times और inner loop प्रत्येक outer iteration में 3 times execute होता है।
In this example, the outer loop executes 3 times, and the inner loop executes 3 times for each outer iteration.
Total executions:
3 × 3 = 9
Nested while Loops :-
Nested Loops केवल for loop के साथ ही नहीं, बल्कि while loop के साथ भी बनाए जा सकते हैं।
English
Nested loops can be created not only with for loops but also with while loops.
Example:
i = 1
while i <= 3:
j = 1
while j <= 3:
print(i, j)
j += 1
i += 1
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Nested Loop for Pattern :-
Nested loops का उपयोग patterns (आकृतियाँ) बनाने के लिए भी किया जाता है।
English
Nested loops are also commonly used to create patterns.
Example:
for i in range(1, 5):
for j in range(i):
print("*", end=" ")
print()
Output:
*
* *
* * *
* * * *
Because:
पहली row में 1 star, दूसरी row में 2 stars, तीसरी row में 3 stars और चौथी row में 4 stars print होते हैं।
English
The first row prints 1 star, the second row prints 2 stars, the third row prints 3 stars, and the fourth row prints 4 stars.