Loop Statements

What Are Loop Statements?

  • Loop statements help us execute a block of code multiple times. They repeat until a specific condition is met or for each item in a collection.

Types of Loop Statements:

  1. For Loop:
    • Used to run a block of code for each element in a collection.
    • Example:

      python
      list_1 = ['apple', 'banana', 'cherry']
      
      for item in list_1:
          print(item)
      
    • Output:

       
      apple
      banana
      cherry
      
  2. While Loop:
    • Used to run a block of code as long as a condition is true.
    • Example:

      python
      list_1 = ['apple', 'banana', 'cherry']
      index = 0
      
      while index < len(list_1):
          print(list_1[index])
          index += 1
      
    • Output:

       
      apple
      banana
      cherry
      

Using for i in range():

  • Execute a block of code for each number in a given range.

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

     
    0
    1
    2
    3
    4
    

Loop Controls:

  1. Break:
  2. Continue:

Summary:

  • Loop statements are vital for repeating actions in your code. Using for and while loops, along with break and continue, allows you to control how and when blocks of code are executed multiple times. Practice these concepts with the exercises to become proficient in using loops in Python!