Loop

Introduction:

  • In Python, you can use a for loop to iterate through all the elements of an array (or list). This is useful for accessing and processing each element in the array.

Example:

  • Here's how you can print each item in the cars array using a for loop:

    python
    cars = ["Ford", "Volvo", "BMW"]
    for x in cars:
        print(x)
    

Output:

Ford
Volvo
BMW

Exercises:

  1. Loop Through a List of Numbers:
    • Write a program to print each number in a list of numbers.

      python
      numbers = [1, 2, 3, 4, 5]
      for num in numbers:
          print(num)
      
  2. Loop Through a List of Strings:
    • Write a program to print each string in a list of strings.

      python
      fruits = ["apple", "banana", "cherry"]
      for fruit in fruits:
          print(fruit)
      
  3. Loop Through and Modify List Elements:
    • Write a program to loop through a list of numbers and print each number multiplied by 2.

      python
      numbers = [1, 2, 3, 4, 5]
      for num in numbers:
          print(num * 2)
      

Summary:

  • In this tutorial, we learned how to loop through array elements using a for loop in Python. This is an essential skill when working with arrays or lists, allowing you to access and process each element individually. Practice using for loops with different types of arrays to get comfortable with this fundamental programming concept!