Loop
Introduction:
- In Python, you can use a
forloop 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
carsarray using aforloop:pythoncars = ["Ford", "Volvo", "BMW"] for x in cars: print(x)
Output:
Ford
Volvo
BMW
Exercises:
- Loop Through a List of Numbers:
Write a program to print each number in a list of numbers.
pythonnumbers = [1, 2, 3, 4, 5] for num in numbers: print(num)
- Loop Through a List of Strings:
Write a program to print each string in a list of strings.
pythonfruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)
- Loop Through and Modify List Elements:
Write a program to loop through a list of numbers and print each number multiplied by 2.
pythonnumbers = [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
forloop in Python. This is an essential skill when working with arrays or lists, allowing you to access and process each element individually. Practice usingforloops with different types of arrays to get comfortable with this fundamental programming concept!