Python For Loop
For Loop
In Python, a for
loop is used to iterate over a sequence (such as a list, tuple, string, or range) and execute a block of code for each element in the sequence. The general syntax of a for
loop is as follows:
# Syntax
for variable in sequence:
# Code to be executed for each element in the sequence
Example:
# Using a for loop with a list
fruits = ["apple", "orange", "banana"]
for fruit in fruits:
print(fruit)
In this example, the for
loop iterates over each element in the fruits
list, and the print
statement is executed for each fruit.
Break Statement
In Python, the break
statement is used to prematurely exit a loop, stopping its execution even if the loop condition is not fully satisfied. This is commonly used with for
loops to terminate the loop based on a certain condition.
Example:
# Using break with for loop
fruits = ["apple", "orange", "banana", "grape", "kiwi"]
for fruit in fruits:
if fruit == "grape":
break
print(fruit)
In the example above, the for
loop iterates through each element in the fruits
list. The break
statement is encountered when the loop reaches "grape," causing the loop to exit prematurely.