Python - Loops - For

In Python, there are two main types of loops:

  • for loop: This loop is used when you want to execute a block of code for a fixed number of times. It is typically used when you have a collection of items, such as a list or a tuple, and you want to perform some operation on each item in the collection. The for loop iterates over each item in the collection and executes the code block once for each item.
  • while loop: This loop is used when you want to execute a block of code repeatedly while a certain condition is true. It is typically used when you don't know in advance how many times you need to execute the code block. The while loop continues to execute the code block as long as the condition is true.

In Python, a for loop is used to iterate over a sequence of values, such as a list, tuple, string, or range. It allows you to execute a block of code for each item in the sequence, without having to manually access each item yourself.

The basic syntax of a for loop in Python is as follows:

for variable in sequence:
    # code to execute for each item in the sequence

Here, variable is a new variable that will be assigned to each item in the sequence, one at a time. The code inside the loop will be executed once for each item in the sequence.

For example, let's say you have a list of numbers, and you want to print out each number in the list. You could do this with a for loop like so:

numbers = [1, 2, 3, 4, 5]
for num in numbers:
    print(num)

In this example, the loop will iterate over each item in the numbers list, assigning the value of each item to the variable num in turn. The print(num) statement will then be executed once for each item, printing out each number in the list on a new line.

You can also use a for loop with a range function to iterate over a sequence of numbers. The range function takes one, two, or three arguments, depending on how you want to use it. Here are some examples:

# Loop through the numbers 0 to 4
for i in range(5):
    print(i)

# Loop through the numbers 1 to 5
for i in range(1, 6):
    print(i)

# Loop through the even numbers from 0 to 10
for i in range(0, 11, 2):
    print(i)

In these examples, the range function is used to generate a sequence of numbers, which the for loop then iterates over. In the first example, the range function generates the sequence 0, 1, 2, 3, 4, which the loop iterates over. In the second example, the range function generates the sequence 1, 2, 3, 4, 5, which the loop iterates over. In the third example, the range function generates the sequence 0, 2, 4, 6, 8, 10, which the loop iterates over.

In general, for loops are very useful for iterating over sequences of values, and they can be used in a wide variety of situations where you need to repeat a block of code for each item in a sequence.