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
Sometimes, you might need to iterate a specific number of times, rather than over the elements of an existing sequence. For this, Python provides the range() function. The range() function generates a sequence of numbers. A common usage is range(n), which generates numbers from 0 up to (but not including) n.
for i in range(5):
print(f"This is iteration number {i}")The range(5) will produce the sequence 0, 1, 2, 3, 4. Therefore, the output will be:
This is iteration number 0
This is iteration number 1
This is iteration number 2
This is iteration number 3
This is iteration number 4
The range() function can also take a start and a step value. For example, range(2, 10, 2) will generate numbers starting from 2, up to (but not including) 10, in steps of 2 (i.e., 2, 4, 6, 8).
for num in range(2, 10, 2):
print(num)This will output: 2 4 6 8
graph TD
A[Start Loop] --> B{Get Next Item from Sequence};
B --> C{Item Available?};
C -- Yes --> D[Execute Loop Body with Item];
D --> B;
C -- No --> E[End Loop];
The for loop is a cornerstone of efficient programming. By mastering its use with various sequences and the range() function, you'll be able to write much more concise and powerful Python code.