Skip to main content

1. What are Loops?

  • Loops are used to repeatedly execute a block of code.
  • They are essential for automating repetitive tasks and iterating over sequences like lists, tuples, strings, etc.
  • Python supports two types of loops:
    1. for loops
    2. while loops

2. for Loop

  • The for loop is used to iterate over a sequence (e.g., list, tuple, string, range) or other iterable objects.
  • Syntax:
Example:
Output:

Using range() in for Loops

  • The range() function generates a sequence of numbers.
  • It is commonly used to iterate a specific number of times.
Example:
Output:

3. while Loop

  • The while loop repeats a block of code as long as a condition is True.
  • Syntax:
Example:
Output:

4. Loop Control Statements

  • These statements alter the flow of loops:
    1. break: Exits the loop immediately.
    2. continue: Skips the rest of the code in the current iteration and moves to the next iteration.
    3. pass: A placeholder for future code (does nothing).
Examples:
  • break:
    Output:
  • continue:
    Output:
  • pass:
    Output:

5. Nested Loops

  • A loop inside another loop is called a nested loop.
  • Commonly used for working with multi-dimensional data structures.
Example:
Output:

6. Iterating Over Sequences

  • Loops can iterate over various sequences like lists, tuples, strings, dictionaries, etc.
Examples:
  • List:
  • String:
  • Dictionary:

7. Additional Examples

  • for Loop:
  • while Loop:
  • Nested Loops:
  • Loop Control:

8. Best Practices

  • Use meaningful variable names for iterators (e.g., name instead of x).
  • Avoid infinite loops in while loops by ensuring the condition eventually becomes False.
  • Use break and continue sparingly to keep the code readable.
  • Use list comprehensions for simple loops that create lists.
Example: