Python For Loop
In Python, a for
loop is used to iterate over a sequence (such as list, tuple, string or dictionary) and execute a block of code repeatedly for each element in the sequence.
Syntax
for element in sequence:
# statements to be executed inside the loop
element
: refers to the current element in the sequence that is being processed at a given iteration of the loop.sequence
: is the sequence of elements that the loop is iterating over.
Example
fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits:
print(fruit)
Output
Apple
Banana
Cherry
Explanation
In this example, we have a list fruits
containing three strings. The for
loop iterates over the elements of the list one by one and assigns each item to the variable fruit
. The print
statement prints each of the elements in the list.
Use
For loops are useful when you want to perform the same action on each element in a sequence. They are commonly used for iterating over lists, tuples, sets, and dictionaries.
Important Points
- The
range()
function is often used withfor
loops to specify the number of times a loop should run. - The
break
statement can be used to terminate afor
loop prematurely. - The
continue
statement can be used to skip the current iteration of afor
loop and move on to the next iteration. - In Python,
for
loops can also be used to iterate over the characters in a string.
Summary
In Python, for
loops are used to iterate over a sequence and execute a block of code repeatedly for each element in the sequence. They are useful for manipulating lists, tuples, sets, and dictionaries. With the help of range()
, break
and continue
, for loops can be used to perform certain actions like conditional execution, printing elements, etc.