search

What is the "for" loop in Python and how to use it?

The "for" loop in Python is used to iterate over a sequence (such as a list, tuple, string, or range) and execute a block of code for each item in the sequence. 

The general syntax is:

for variable in sequence:
    # code to be executed

Here, **sequence** is the list of elements over which the loop will iterate, and **variable** is a variable that takes on each value in **sequence** in each iteration. For example, to print the items in a list, you can use a for loop like this:

fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    print(fruit)

This would output:

apple
banana
cherry

Related Questions You Might Be Interested