Python

For Loops

YouTube

For loops are a type of control flow statement in Python that allow you to iterate over a sequence of items, such as a list or a string. For loops are used to repeat a block of code a certain number of times, or until a certain condition is met.

To create a for loop in Python, you use the for keyword followed by a variable name, in, and a sequence. The block of code that follows the for loop is indented, and the indented block is executed once for each item in the sequence.

For Loop

Here is an example of a for loop in Python:

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

for fruit in fruits:
    print(fruit)

In this example, the for loop iterates over the fruits list and prints each item to the console. The output of this code would be:

apple
banana
cherry
Looping through a range

You can also use the range() function to create a sequence of numbers to iterate over. The range() function takes in three arguments: start, stop, and step. The start argument is the first number in the sequence, the stop argument is the number to stop at (not including this number), and the step argument is the number to count by. Here is an example using the range function:

for i in range(0, 10, 2):
    print(i)

In this example, the for loop iterates over a sequence of numbers starting at 0, stopping at 10 (not including 10), and counting by 2. The output of this code would be:

0
2
4
6
8
Enumerate

You can also use the enumerate() function to iterate over a sequence and get the index and value of each item. Here is an example using the enumerate() function:

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

for i, fruit in enumerate(fruits):
    print(i, fruit)

In this example, the for loop iterates over the fruits list and prints the index and value of each item. The output of this code would be:

0 apple
1 banana
2 cherry

There are a few things to keep in mind when using for loops in Python. First, it’s important to make sure your code is properly indented, as this is how Python determines which code belongs in the for loop. Second, you should be careful not to create an infinite loop by forgetting to update the loop variable or by not including a way to exit the loop. Finally, you should be mindful of the performance of your for loops, as they can take a long time to execute if you are iterating over a large sequence