Python for loop
In Python, the for loop is used to iterate over a sequence (such as a list, tuple, string, or range) or any iterable object. It allows you to execute a block of code repeatedly for each item in the sequence. The basic syntax for a for loop in Python is as follows:
for item in sequence:
# code block to execute for each item
Here's an example that demonstrates the usage of a for loop in Python:
# Example 1: Iterate over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# cherry
# Example 2: Iterate over a string
message = "Hello, World!"
for char in message:
print(char)
# Output:
# H
# e
# l
# l
# o
# ,
#
# W
# o
# r
# l
# d
# !
In the first example, the for loop iterates over each item in the fruits list. For each iteration, the variable fruit takes on the value of the current item, and the code block inside the loop (indented) is executed. In this case, the current fruit is printed to the console.
In the second example, the for loop iterates over each character in the message string. The variable char takes on the value of the current character, and the code block inside the loop is executed. Here, each character is printed to the console.
The for loop is a powerful construct in Python for repetitive tasks. It allows you to process each item in a sequence or iterate over a range of numbers, making it useful for various programming scenarios.