Python For Loop
A for
loop in Python is a control flow statement that allows you to iterate over a sequence of elements, such as a list, tuple, or string. For loop body define by indentation (whitespaces 'TAB'). The basic syntax for the for
loop is as follows:
for element in sequence:
# code to be executed for each element in the sequence
Example:
for i in range(1, 11):
print(i)
In the above example, the range
function generates a sequence of numbers from 1 to 10, and the for
loop iterates over this sequence, executing the code block for each number.
The else
clause in a for
loop is optional, and it is executed after the loop terminates, but only if the loop terminates normally (i.e., not because of a break
statement). The syntax for the for
loop with an else
clause is as follows:
for element in sequence:
# code to be executed for each element in the sequence
else:
# code to be executed after the loop terminates normally
Here's an example that searches for a number in a list, and prints a message if the number is not found:
numbers = [1, 2, 3, 4, 5]
search_number = 6
for number in numbers:
if number == search_number:
print(f"{search_number} found in the list")
break
else:
print(f"{search_number} not found in the list")
In this example, the for
loop iterates over the numbers
list, and the if
statement inside the loop checks if the current number is equal to the search_number
. If the search_number
is found, the break
statement is executed to terminate the loop, and the else
clause is not executed. If the loop terminates normally, without executing a break
statement, the else
clause is executed and a message indicating that the search_number
was not found is printed.