Python for Loops
Python for loops are used to iterate over a sequence (such as a list, tuple, string, or range) or any iterable object. They allow you to perform a set of instructions repeatedly for each item in the sequence. The basic syntax of a for loop in Python is as follows:
for item in sequence: # Code block to be executed
item represents a variable that will take on the value of each item in the sequence, and
sequence is the iterable object you want to iterate over. The code block following the colon is indented and contains the instructions that will be executed for each item.
Let’s look at a few examples to illustrate the usage of for loops:
Example 1: Iterating over a list
fruits = ["apple", "banana", "orange"] for fruit in fruits: print(fruit)
apple banana orange
Example 2: Iterating over a string
message = "Hello, world!" for char in message: print(char)
H e l l o , w o r l d !
Example 3: Using the range function
for num in range(1, 5): print(num)
1 2 3 4
In this last example, the
range() function generates a sequence of numbers from 1 to 4 (the second argument is exclusive), and the for loop iterates over each number in the sequence.
You can also combine for loops with conditional statements (if-else) and other control flow statements to create more complex logic within the loop.