For Loops

In Python, loops allow you to execute a block of code repeatedly, either a specified number of times or until a certain condition is met. There are two types of loops in Python: for loops and while loops.

The for loop is used to iterate over a sequence of elements, such as a list, tuple, or string, and execute a block of code for each element in the sequence. Here is a basic example of a for loop in Python:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

In this example, the for loop is used to iterate over the elements of the list fruits. The for keyword is followed by a variable, fruit, which is used to store each element of the list as the loop iterates over the list. The in keyword is used to specify the sequence that the loop will iterate over, which in this case is the list fruits. The block of code inside the loop, indented by four spaces, will be executed for each element in the list.

When the loop starts, the first element of the list, "apple", will be assigned to the variable fruit, and the code inside the loop will be executed, printing "apple". The loop will then move to the next element in the list, "banana", and repeat the process. This will continue until all elements in the list have been processed.

The for loop can also be used with other types of sequences, such as tuples, strings, and dictionaries. Here is an example of a for loop that iterates over a string:

name = "John Doe"

for char in name:
    print(char)

In this example, the for loop is used to iterate over the characters in the string name. The variable char is used to store each character as the loop iterates over the string. The code inside the loop will be executed for each character in the string, printing each character on a separate line.

Another way to use the for loop is to iterate over a range of numbers. The range function can be used to generate a sequence of numbers, which can be used in a for loop. Here is an example:

for i in range(5):
    print(i)

In this example, the range function is used to generate a sequence of numbers from 0 to 4 (the range function generates a sequence of numbers up to, but not including, the specified end number). The for loop is used to iterate over the numbers in the sequence, and the variable i is used to store each number as the loop iterates. The code inside the loop will be executed for each number in the sequence, printing each number on a separate line.

The for loop is a powerful tool for iterating over sequences and performing repetitive tasks in Python. By using the for loop, you can automate tasks that would otherwise require manual processing, making your code more efficient and easier to maintain. Additionally, the for loop provides a convenient way to work with sequences of data in your programs, such as lists, tuples, strings, and ranges.