Online Computer Courses Classes and Training Program

Python Programming में Loops: एक Complete Tutorial in Hindi

 
Loops in Python Programming.

Loops Tutorial in Python Programming

(Python Programming में Loops का परिचय)

Python programming में, loops का उपयोग repetitive tasks को simplify करने के लिए किया जाता है। Loops का मतलब है किसी process को बार-बार दोहराना जब तक कोई condition satisfy न हो जाए। Python में मुख्यतः दो प्रकार के loops होते हैं:

  • for loop
  • while loop

आइए इन्हें detail में समझते हैं।


1. For Loop

For loop का उपयोग तब किया जाता है जब आपको किसी sequence (जैसे list, tuple, string, या range) को iterate करना हो।

Syntax:

for variable in sequence:
    # code block

Example:

# List के elements को print करना
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

Output:

apple  
banana  
cherry  

Range Function के साथ For Loop

# 1 से 5 तक numbers print करना
for i in range(1, 6):
    print(i)

Output:

1  
2  
3  
4  
5  

2. While Loop

While loop का उपयोग तब किया जाता है जब आपको condition-based looping करनी हो।

Syntax:

while condition:
    # code block

Example:

# 1 से 5 तक numbers print करना
i = 1
while i <= 5:
    print(i)
    i += 1

Output:

1  
2  
3  
4  
5  

Loop Control Statements

Loops को manage और control करने के लिए Python में कुछ विशेष statements हैं:

1. Break Statement:

Break loop को बीच में ही terminate कर देता है।

for i in range(1, 10):
    if i == 5:
        break
    print(i)

Output:

1  
2  
3  
4  

2. Continue Statement:

Continue current iteration को skip करके loop को अगले iteration पर ले जाता है।

for i in range(1, 6):
    if i == 3:
        continue
    print(i)

Output:

1  
2  
4  
5  

3. Pass Statement:

Pass एक null statement है। इसका उपयोग तब किया जाता है जब हमें loop में कोई action perform नहीं करना हो।

for i in range(1, 4):
    pass

Nested Loops

Loop के अंदर एक और loop को nested loop कहते हैं।

# Nested loop example
for i in range(1, 4):
    for j in range(1, 4):
        print(f"i={i}, j={j}")

Output:

i=1, j=1  
i=1, j=2  
i=1, j=3  
i=2, j=1  
i=2, j=2  
i=2, j=3  
i=3, j=1  
i=3, j=2  
i=3, j=3  

Practical Example: Multiplication Table

# Multiplication table using for loop
num = 2
for i in range(1, 11):
    print(f"{num} x {i} = {num * i}")

Output:

2 x 1 = 2  
2 x 2 = 4  
2 x 3 = 6  
...  
2 x 10 = 20  

Conclusion

Loops Python programming का एक महत्वपूर्ण हिस्सा हैं जो repetitive tasks को आसान बनाते हैं। For loop और While loop दोनों का उपयोग अलग-अलग स्थितियों में किया जाता है। Loop control statements (break, continue, pass) और nested loops का सही तरीके से उपयोग करके आप complex problems को efficiently solve कर सकते हैं।

Python में loops को practice करने के लिए आपको code लिखने और उसे run करने का प्रयास करना चाहिए। Happy Coding!


यहाँ कुछ Python programming examples दिए गए हैं जो loops के concepts को और स्पष्ट करेंगे:


1. Even Numbers in a Range (For Loop)

# 1 से 20 के बीच सभी even numbers print करना
for num in range(1, 21):
    if num % 2 == 0:
        print(num)

Output:

2  
4  
6  
8  
10  
12  
14  
16  
18  
20  

2. Factorial Calculation (While Loop)

# किसी number का factorial calculate करना
num = 5
factorial = 1
while num > 0:
    factorial *= num
    num -= 1
print("Factorial is:", factorial)

Output:

Factorial is: 120

3. Sum of Digits of a Number (While Loop)

# किसी number के digits का sum निकालना
number = 1234
sum_of_digits = 0
while number > 0:
    digit = number % 10
    sum_of_digits += digit
    number //= 10
print("Sum of digits:", sum_of_digits)

Output:

Sum of digits: 10

4. Printing a Pyramid Pattern (Nested Loops)

# Pyramid pattern print करना
rows = 5
for i in range(1, rows + 1):
    for j in range(i):
        print("*", end=" ")
    print()

Output:

*  
* *  
* * *  
* * * *  
* * * * *  

5. Finding Prime Numbers (For Loop)

# 1 से 50 के बीच prime numbers print करना
for num in range(2, 51):
    is_prime = True
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            is_prime = False
            break
    if is_prime:
        print(num)

Output:

2  
3  
5  
7  
11  
13  
17  
19  
23  
29  
31  
37  
41  
43  
47  

6. Reverse a String (For Loop)

# String को reverse करना
string = "Python"
reversed_string = ""
for char in string:
    reversed_string = char + reversed_string
print("Reversed String:", reversed_string)

Output:

Reversed String: nohtyP

7. Infinite Loop Example (While Loop)

# Infinite loop example (use with caution)
count = 1
while True:
    print("This is an infinite loop:", count)
    count += 1
    if count > 5:  # Loop break condition
        break

Output:

This is an infinite loop: 1  
This is an infinite loop: 2  
This is an infinite loop: 3  
This is an infinite loop: 4  
This is an infinite loop: 5  

8. Table of Any Number (For Loop)

# किसी number की table print करना
number = int(input("Enter a number: "))
for i in range(1, 11):
    print(f"{number} x {i} = {number * i}")

Input:

Enter a number: 7

Output:

7 x 1 = 7  
7 x 2 = 14  
7 x 3 = 21  
...  
7 x 10 = 70  

9. Checking Palindrome (For Loop)

# Check if a string is palindrome
string = "madam"
reversed_string = string[::-1]
if string == reversed_string:
    print("The string is a palindrome")
else:
    print("The string is not a palindrome")

Output:

The string is a palindrome

10. Fibonacci Series (While Loop)

# Fibonacci series print करना
n = 10
a, b = 0, 1
count = 0
while count < n:
    print(a, end=" ")
    a, b = b, a + b
    count += 1

Output:

0 1 1 2 3 5 8 13 21 34




1. Even Numbers in a Range (For Loop)

Code Explanation:

# 1 से 20 के बीच सभी even numbers print करना
for num in range(1, 21):  # 1 से 20 तक के numbers पर loop चलेगा
    if num % 2 == 0:      # Check करें कि number even है या नहीं
        print(num)        # अगर number even है, तो उसे print करें

How it Works:

  • range(1, 21): यह 1 से 20 तक numbers generate करता है।
  • num % 2 == 0: अगर कोई number 2 से completely divide हो सकता है, तो वह even होता है।
  • Output में सिर्फ even numbers (जैसे 2, 4, 6, ...) print होंगे।

2. Factorial Calculation (While Loop)

Code Explanation:

num = 5                  # जिसका factorial निकालना है
factorial = 1            # Result को store करने के लिए variable
while num > 0:           # जब तक num 0 से बड़ा है, loop चलेगा
    factorial *= num      # factorial = factorial * num
    num -= 1              # num को 1 से reduce करें
print("Factorial is:", factorial)  # Result print करें

How it Works:

  • Suppose num = 5 है।
    • पहली iteration: factorial = 1 × 5 = 5
    • दूसरी iteration: factorial = 5 × 4 = 20
    • तीसरी iteration: factorial = 20 × 3 = 60
    • चौथी iteration: factorial = 60 × 2 = 120
    • पाँचवीं iteration: factorial = 120 × 1 = 120
  • जब num = 0, loop रुक जाता है, और result print होता है।

3. Sum of Digits of a Number (While Loop)

Code Explanation:

number = 1234           # Input number
sum_of_digits = 0       # Sum store करने के लिए variable
while number > 0:       # जब तक number 0 से बड़ा है, loop चलेगा
    digit = number % 10  # Last digit निकालें
    sum_of_digits += digit  # Sum में add करें
    number //= 10         # Number को 10 से divide करें (last digit remove करें)
print("Sum of digits:", sum_of_digits)  # Final sum print करें

How it Works:

  • For 1234:
    • First iteration: digit = 4, sum_of_digits = 0 + 4 = 4, number = 123
    • Second iteration: digit = 3, sum_of_digits = 4 + 3 = 7, number = 12
    • Third iteration: digit = 2, sum_of_digits = 7 + 2 = 9, number = 1
    • Fourth iteration: digit = 1, sum_of_digits = 9 + 1 = 10, number = 0

4. Printing a Pyramid Pattern (Nested Loops)

Code Explanation:

rows = 5                   # Pyramid में rows की संख्या
for i in range(1, rows + 1):   # Outer loop rows के लिए
    for j in range(i):         # Inner loop उस row के लिए stars print करेगा
        print("*", end=" ")    # Star print करें
    print()                    # New line for next row

How it Works:

  • Outer loop rows को control करता है।
  • Inner loop हर row में stars की संख्या को control करता है।
  • Example for 5 rows:
    Row 1: *
    Row 2: * *
    Row 3: * * *
    Row 4: * * * *
    Row 5: * * * * *
    

5. Finding Prime Numbers (For Loop)

Code Explanation:

for num in range(2, 51):             # 2 से 50 तक के numbers के लिए loop
    is_prime = True                 # Prime check करने के लिए flag
    for i in range(2, int(num**0.5) + 1):  # 2 से sqrt(num) तक check करें
        if num % i == 0:            # अगर num divisible है
            is_prime = False        # तो यह prime नहीं है
            break                   # Inner loop से बाहर निकलें
    if is_prime:                    # अगर prime है, तो print करें
        print(num)

How it Works:

  • Prime numbers वे होते हैं जो सिर्फ 1 और खुद से divisible होते हैं।
  • Inner loop में sqrt(num) तक check करना efficient है।
  • Example:
    • 2, 3, 5, 7, ... को prime identify किया जाता है।

6. Reverse a String (For Loop)

Code Explanation:

string = "Python"            # Input string
reversed_string = ""         # Result store करने के लिए variable
for char in string:          # हर character के लिए loop
    reversed_string = char + reversed_string  # Reverse में add करें
print("Reversed String:", reversed_string)  # Result print करें

How it Works:

  • String को reverse करने के लिए हर character को पहले जोड़ते हैं।
  • Example:
    • For "Python":
      • First iteration: reversed_string = "P"
      • Second iteration: reversed_string = "yP"
      • Final reversed_string = "nohtyP"

7. Table of Any Number (For Loop)

Code Explanation:

number = int(input("Enter a number: "))  # User input
for i in range(1, 11):                  # 1 से 10 तक numbers के लिए loop
    print(f"{number} x {i} = {number * i}")  # Table format में print करें

How it Works:

  • Input number से table generate होता है।
  • Example for 7:
    7 x 1 = 7  
    7 x 2 = 14  
    7 x 3 = 21  
    ...
    7 x 10 = 70  
    

8. Fibonacci Series (While Loop)

Code Explanation:

n = 10                      # कितने numbers चाहिए
a, b = 0, 1                 # Initial values
count = 0                   # Loop counter
while count < n:            # जब तक n numbers न हो जाएं
    print(a, end=" ")       # Current number print करें
    a, b = b, a + b         # अगले दो numbers के लिए update करें
    count += 1              # Counter increment करें

How it Works:

  • Fibonacci series में हर number, पिछले दो numbers का sum होता है।
  • Example for n = 10:
    0 1 1 2 3 5 8 13 21 34  
    




Multiple Choice Questions (MCQs)

  1. Which loop is used when the number of iterations is not known beforehand?
    a) For loop
    b) While loop
    c) Do-while loop
    d) Nested loop
    Answer: b) While loop

  2. What will be the output of the following code?

    for i in range(3):
        print(i, end=" ")
    

    a) 0 1 2
    b) 1 2 3
    c) 0 1 2 3
    d) 1 2
    Answer: a) 0 1 2

  3. In Python, what is the keyword used to terminate a loop prematurely?
    a) terminate
    b) exit
    c) break
    d) continue
    Answer: c) break

  4. Which of the following is a null statement in Python?
    a) break
    b) continue
    c) pass
    d) None of the above
    Answer: c) pass

  5. What is the output of the following code?

    i = 1
    while i < 4:
        print(i, end=" ")
        i += 1
    

    a) 1 2 3 4
    b) 1 2 3
    c) 1 2
    d) Infinite loop
    Answer: b) 1 2 3


Fill in the Blanks

  1. A for loop is used to iterate over a sequence like a list, tuple, or string.
  2. The break statement is used to terminate the loop prematurely.
  3. The continue statement is used to skip the current iteration of the loop.
  4. range(start, stop) generates numbers starting from start and stops just before stop.
  5. A loop inside another loop is called a nested loop.

True/False

  1. A while loop always executes at least once.
    False (It executes only if the condition is true.)

  2. The pass statement does nothing when executed.
    True

  3. A for loop can iterate over a dictionary.
    True

  4. In Python, the range function includes the stop value in its output.
    False (The stop value is excluded.)

  5. An infinite loop can only occur with a while loop, not a for loop.
    False (Both loops can result in infinite loops if not handled properly.)


These MCQs, fill-in-the-blanks, and true/false questions will help test the understanding of loops in Python programming.



Question-Answer Based on Loops in Python

1. Short Answer Questions:

  1. What is the purpose of a loop in programming?
    Answer: A loop is used to execute a block of code repeatedly until a specified condition is met.

  2. What are the two types of loops available in Python?
    Answer: The two types of loops in Python are:

    • for loop
    • while loop
  3. What does the break statement do in a loop?
    Answer: The break statement is used to exit a loop prematurely, regardless of the condition.

  4. What is the difference between break and continue?
    Answer:

    • break: Exits the loop completely.
    • continue: Skips the current iteration and moves to the next iteration.
  5. What is the output of the following code?

    for i in range(5):
        if i == 3:
            break
        print(i)
    

    Answer:

    0  
    1  
    2  
    

2. Fill in the Blanks:

  1. The range() function is commonly used with a for loop to generate a sequence of numbers.
  2. The while loop executes as long as the condition evaluates to True.
  3. The pass statement is used as a placeholder in a loop or function.
  4. A loop inside another loop is called a nested loop.
  5. The continue statement skips the current iteration of the loop.

3. True/False Questions:

  1. A for loop is used when the number of iterations is known beforehand.
    True

  2. The while loop always executes at least once.
    False (It depends on the condition.)

  3. A loop can be infinite if there is no condition to terminate it.
    True

  4. The break statement skips the current iteration of the loop.
    False (It terminates the loop.)

  5. In Python, you can use a loop to iterate over a string.
    True


4. Multiple Choice Questions (MCQs):

  1. What is the syntax for a for loop in Python?
    a) for i in range():
    b) for i in range(n):
    c) for i to n:
    d) for i in n:
    Answer: b) for i in range(n):

  2. Which of the following is an infinite loop?

    a) while True: print("Hello")  
    b) for i in range(5): print(i)  
    c) while False: print("Hi")  
    d) for i in []: print(i)  
    

    Answer: a) while True: print("Hello")

  3. What is the output of the following code?

    for i in range(1, 4):
        for j in range(i):
            print(j, end=" ")
        print()
    

    a)

    0  
    0 1  
    0 1 2  
    

    b)

    1  
    1 2  
    1 2 3  
    

    c) Infinite loop
    d) Error
    Answer: a)

    0  
    0 1  
    0 1 2  
    
  4. What happens if the condition in a while loop is never False?
    a) The loop runs infinite times.
    b) The loop executes only once.
    c) The loop stops automatically after 10 iterations.
    d) The code gives a syntax error.
    Answer: a) The loop runs infinite times.

  5. Which keyword is used to skip to the next iteration of a loop?
    a) break
    b) pass
    c) skip
    d) continue
    Answer: d) continue


These questions and answers provide a complete understanding of Python loops. 



Additional Questions and Answers on Loops in Python


1. Short Answer Questions

  1. What is a nested loop?
    Answer: A loop inside another loop is called a nested loop. The inner loop is executed completely for every single iteration of the outer loop.

  2. What does the else clause do in loops?
    Answer: The else clause in a loop executes after the loop finishes all iterations, but it is skipped if the loop is terminated with a break statement.

  3. Can you use else with a while loop? Give an example.
    Answer: Yes, the else clause can be used with a while loop.

    i = 1
    while i < 3:
        print(i)
        i += 1
    else:
        print("Loop completed")
    

    Output:

    1  
    2  
    Loop completed  
    
  4. What is the difference between a for loop and a while loop?
    Answer:

    • A for loop is used when the number of iterations is known beforehand.
    • A while loop is used when the number of iterations depends on a condition being true.
  5. What is the output of the following code?

    for i in range(1, 6):
        if i == 4:
            break
        print(i)
    else:
        print("Done")
    

    Answer:

    1  
    2  
    3  
    

2. Fill in the Blanks

  1. A while loop checks the condition before executing the code block.
  2. The for loop is used for iterating over sequences like lists, strings, or tuples.
  3. The break statement is used to terminate the loop entirely.
  4. The else clause in a loop executes only if the loop completes successfully without encountering a break.
  5. The continue statement is used to skip the current iteration of a loop.

3. True/False Questions

  1. A loop can have multiple break statements.
    True

  2. The range function generates a sequence that includes the stop value.
    False (The stop value is excluded.)

  3. The continue statement stops the entire loop.
    False (It skips the current iteration and moves to the next one.)

  4. The pass statement is a placeholder and does nothing when executed.
    True

  5. The else block in a loop executes even if a break statement is encountered.
    False


4. Multiple Choice Questions (MCQs)

  1. What will be the output of the following code?

    i = 0
    while i < 3:
        print(i, end=" ")
        i += 1
    else:
        print("Done")
    

    a) 0 1 2
    b) 0 1 2 Done
    c) Done
    d) Infinite loop
    Answer: b) 0 1 2 Done

  2. What is the output of the following code?

    for i in range(3):
        for j in range(2):
            print(i, j)
    

    a)

    0 0  
    0 1  
    1 0  
    1 1  
    2 0  
    2 1  
    

    b)

    0 1  
    1 2  
    2 3  
    

    c) Infinite loop
    d) Error
    Answer: a)

  3. Which statement will correctly print all odd numbers between 1 and 10?
    a)

    for i in range(1, 10):
        if i % 2 == 0:
            print(i)
    

    b)

    for i in range(1, 11, 2):
        print(i)
    

    c)

    for i in range(1, 11):
        if i % 2 != 0:
            print(i)
    

    d) Both b and c
    Answer: d) Both b and c

  4. What will happen if the condition in a while loop never becomes False?
    a) The loop executes only once.
    b) The loop runs infinitely.
    c) The loop will not execute.
    d) Syntax error occurs.
    Answer: b) The loop runs infinitely.

  5. What is the correct syntax for a for loop in Python?
    a) for i to n:
    b) for i = 1 to 10:
    c) for i in range(1, 10):
    d) for i range(10):
    Answer: c) for i in range(1, 10):


5. Descriptive Questions

  1. Write a Python program to find the sum of all even numbers between 1 and 50 using a for loop.
    Answer:

    total = 0
    for i in range(1, 51):
        if i % 2 == 0:
            total += i
    print("Sum of even numbers:", total)
    
  2. Explain the purpose of the range() function in Python loops.
    Answer: The range() function generates a sequence of numbers, which is commonly used in for loops for iteration. It can take up to three arguments: start, stop, and step.

  3. Write a Python program to print the multiplication table of a given number using a while loop.
    Answer:

    num = int(input("Enter a number: "))
    i = 1
    while i <= 10:
        print(f"{num} x {i} = {num * i}")
        i += 1
    

These additional questions and answers cover a range of difficulty levels and provide a strong understanding of Python loops.







Post a Comment

0 Comments