So far, we've learned how to execute code line by line and how to make simple decisions using if statements. But what if you need to perform an action multiple times? This is where loops come in! Loops are fundamental to programming as they allow us to automate repetitive tasks, saving us a tremendous amount of time and effort.
Python offers two primary types of loops: the for loop and the while loop. Each has its own strengths and is suited for different scenarios.
The for loop is designed to iterate over a sequence (like a list, tuple, string, or range) and execute a block of code for each item in that sequence. It's perfect when you know exactly how many times you want to repeat an action, or when you want to process each element of a collection.
The general syntax for a for loop looks like this:
for item in sequence:
# Code to be executed for each itemLet's break this down:
for: This keyword initiates the loop.item: This is a variable that will take on the value of each element in thesequenceone by one during each iteration.in: This keyword connects theitemto thesequence.sequence: This is the iterable object (like a list or a string) that the loop will go through.- The colon
:marks the end of theforstatement and the beginning of the indented code block that will be repeated.
Here's a simple example using a list of fruits:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)When you run this code, it will output: apple banana cherry
Notice how the print(fruit) statement is executed once for each element in the fruits list, with the fruit variable holding the current element during each iteration.