A for
loop in Python is a control flow statement that allows you to iterate over a sequence (such as a list, tuple, string, or range) and execute a block of code for each item in that sequence. Unlike a while
loop, where the number of iterations depends on a condition, the for
loop runs for a fixed number of iterations based on the length of the sequence being looped over.
for
Loop**item**
: A variable that takes the value of each element in the sequence on each iteration.**sequence**
: The collection (list, tuple, string, etc.) that the loop iterates over.for
Loopfruits
list, printing each fruit: "apple," "banana," and "cherry."for
Loop Worksitem
variable.item
.item
, and the process repeats.for
LoopYou can use the for
loop to iterate over the elements of a list, tuple, or any other collection.
The for
loop can be used to iterate over each character in a string.
You can use the for
loop to iterate over the keys and values in a dictionary.
range()
Function with a for
LoopThe range()
function generates a sequence of numbers, making it easy to loop over a specific range of values.
range(5)
function generates numbers starting from 0 up to (but not including) 5.range()
range(2, 10, 2)
function specifies a start of 2, an end of 10, and a step of 2.for
Loop with break
and continue
**break**
Statement:The break
statement terminates the loop immediately, regardless of whether all items have been iterated over.
break
num
equals 5 due to the break
statement.**continue**
Statement:The continue
statement skips the current iteration and moves on to the next one.
continue
else
Clause with a for
LoopPython allows an else
clause to be used with a for
loop. The else
block is executed after the loop completes all its iterations unless the loop is terminated with a break
.
else
block runs after the loop has printed all numbers from 0 to 4, printing "Loop finished."for
LoopYou can use the for
loop to sum the values in a list.
total
, which ends up as 15.The for
loop can be used to find and print even numbers in a range.
**for**
Loops:You can nest for
loops to iterate over multiple dimensions, such as in a matrix or a list of lists.
The for
loop in Python is a versatile control structure that allows you to iterate over sequences like lists, tuples, and strings. It is useful for situations where you need to perform repetitive tasks or process items in a sequence. Combined with features like the range()
function, break
, and continue
statements, the for
loop becomes a powerful tool for efficiently handling iterations in your Python programs.