About 'for' loop in Python
In Python, the 'for' loop is used to iterate over a sequence or any iterable object such as a list, tuple, string, or range.
It repeatedly executes a block of code until the iteration of the sequence is completed.
When the iterator is exhausted, the else clause (if present) is executed, and the loop terminates.
Basic syntax of 'for' loop
In the above syntax, 'for' is the keyword that starts the for loop.
'for' is followed by a conditional statement (item in sequence
) where 'item' is a variable that represents the element/item of the sequence being iterated over. You can choose your variable name.
'sequence' is the iterable object (a list, tuple, string, range, or any other iterable) over which the loop iterates. You need to replace it with your iterable object.
The sequence is followed by a colon (:) which is part of the syntax.
The block of code must have proper indentation (at least one space at the beginning of the code for indentation).
Using 'for' loop in Python
1. Create a variable 'fruit_list' and assign a list to the variable (fruit_list = ["Apple", "Banana", "Orange"]
).
2. Create a for loop with fruit_list object (for fruit in fruit_list:
) where fruit is the item of the fruit_list, fruit_list is a list object, and the colon (:) is part of the syntax.
3. Now create a block of code that will be executed during each iteration of the loop. The print message print(fruit)
is the block of code to be executed.
Please take a closer look at the following example:
Example of for loop using list
Output of the above example
Apple Banana Orange
In the same way, you can create for loop using tuple, string, and range. Check Live Code Playground for examples.
Using else in for loop
You can add an 'else' block to a for loop.
The code inside the 'else' block runs once when the iteration of the sequence is completed.
Please take a closer look at the following example:
Example of else in for loop
Output of the above example
Apple Banana Orange For loop terminated & else block runs.