Now that we've explored how to make decisions with if statements, let's dive into another fundamental control flow structure: the for loop. Loops are essential for automating repetitive tasks, and the for loop in Python is particularly powerful for iterating over sequences.
Think of a sequence as an ordered collection of items. In Python, common sequence types include strings (sequences of characters), lists (ordered collections of various items), and tuples (immutable ordered collections). The for loop allows us to process each item within these sequences one by one, without us having to manually access each element.
The basic syntax of a for loop is quite straightforward. It consists of the keyword for, followed by a variable that will hold the current item from the sequence, the keyword in, and then the sequence itself. The code to be executed for each item is indented below the for statement.
for item in sequence:
# Code to execute for each item
print(item)Let's illustrate this with an example. Imagine you have a list of your favorite fruits and you want to print each one. The for loop makes this incredibly simple.
fruits = ["apple", "banana", "cherry", "date"]
for fruit in fruits:
print(f"I like {fruit}")In this code, fruit is the variable that takes on the value of each item in the fruits list during each iteration of the loop. The first time through, fruit will be 'apple', then 'banana', and so on, until all items are processed. The output will be:
I like apple
I like banana
I like cherry
I like date
Strings are also sequences, so you can iterate over them character by character.
greeting = "Hello"
for char in greeting:
print(char)This will output each character of the string on a new line: H e l l o