whenever life put's you in a tough situtation, never say why me! but, try me!

Control Flow: Loops in Python

Loops allow you to execute a block of code multiple times, depending on a condition. Python provides two primary types of loops:

  • for loop: Used for iterating over a sequence (such as a list, tuple, or string).
  • while loop: Continues executing as long as a given condition is True.

Additionally, Python has loop control statements like break, continue, and pass, which control the flow of loops.


Subtopic 1: For Loops

The for loop is typically used when you have a sequence (such as a list, tuple, dictionary, set, or string) to iterate over.

Syntax
for item in sequence:
    # Code block executed for each item in the sequence
Example
# Example of for loop with a list
fruits = ['apple', 'banana', 'cherry']

for fruit in fruits:
    print(fruit)

Output:

apple
banana
cherry
Explanation:
  • The for loop iterates over each element in the fruits list and prints it.

You can also use the range() function to generate a sequence of numbers for iteration.

# Example using range()
for i in range(5):  # This will print numbers from 0 to 4
    print(i)

Output:

0
1
2
3
4

Subtopic 2: While Loops

The while loop executes a block of code as long as the given condition is True. If the condition is initially False, the block of code will not be executed.

Syntax
while condition:
    # Code block executed as long as condition is True
Example
# Example of while loop
count = 0

while count < 5:
    print(count)
    count += 1  # Increment the counter to avoid infinite loop

Output:

0
1
2
3
4
Explanation:
  • The while loop checks if the count is less than 5. If True, it prints the value of count and increments it. The loop stops when count reaches 5.

Subtopic 3: Nested Loops

You can place one loop inside another. This is useful when working with multi-dimensional data structures, such as a list of lists.

Syntax
for outer_item in outer_sequence:
    for inner_item in inner_sequence:
        # Code block executed for each combination of outer_item and inner_item
Example
# Example of nested for loop
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

for row in matrix:
    for element in row:
        print(element, end=" ")
    print()  # For newline after each row

Output:

1 2 3 
4 5 6 
7 8 9
Explanation:
  • The outer for loop iterates over each row of the matrix (which is a list of lists), and the inner for loop iterates over each element of the current row.

Subtopic 4: Loop Control Statements (break, continue, pass)

Control statements help you modify the flow of execution within loops.

  1. break: Exits the loop entirely.
  2. continue: Skips the current iteration and moves to the next iteration.
  3. pass: A placeholder that does nothing; useful when you have a loop or condition with no code in it.
break Example
# Example of break in a loop
for i in range(10):
    if i == 5:
        break  # Exits the loop when i is 5
    print(i)

Output:

0
1
2
3
4
continue Example
# Example of continue in a loop
for i in range(10):
    if i % 2 == 0:
        continue  # Skips even numbers
    print(i)

Output:

1
3
5
7
9
pass Example
# Example of pass in a loop
for i in range(3):
    if i == 2:
        pass  # Does nothing when i is 2
    print(i)

Output:

0
1
2
Explanation:
  • break: The loop terminates when i == 5.
  • continue: The loop skips printing even numbers.
  • pass: The loop does nothing when i == 2.

Tasks

  1. Task 1: Print Even Numbers Using For Loop

    • Write a Python program that prints all even numbers between 1 and 20 using a for loop.
    for i in range(1, 21):
        if i % 2 == 0:
            print(i)
    
  2. Task 2: Sum of Numbers in a List Using For Loop

    • Write a program that calculates the sum of all numbers in a list using a for loop.
    numbers = [1, 2, 3, 4, 5]
    total = 0
    for num in numbers:
        total += num
    print("Sum:", total)
    
  3. Task 3: Count Down Using While Loop

    • Write a program that counts down from 10 to 1 using a while loop.
    count = 10
    while count > 0:
        print(count)
        count -= 1
    
  4. Task 4: Nested Loop for Multiplication Table

    • Write a Python program that generates a multiplication table (from 1 to 5) using a nested for loop.
    for i in range(1, 6):
        for j in range(1, 6):
            print(f"{i} * {j} = {i * j}")
        print()  # Print a newline after each row
    
  5. Task 5: Skip Odd Numbers Using Continue

    • Write a program that prints all numbers from 1 to 10, but skips odd numbers using the continue statement.
    for i in range(1, 11):
        if i % 2 != 0:
            continue
        print(i)
    
  6. Task 6: Infinite Loop with Break

    • Write a program that creates an infinite loop that will print "Hello, World!" until the user enters "stop".
    while True:
        user_input = input("Enter a command (type 'stop' to exit): ")
        if user_input == 'stop':
            break
        print("Hello, World!")