In this tutorial, we will learn about the python loop. which is used to iterable or iterator to our python code
What is a for loop in Python?
A for loops in python is used to iterate over a sequence, a list, a tuple, a dictionary, a set, or a string. With for loop, we can execute a particular set of statements one at each time.
Iterating over a sequence is called traversal.
python for loop syntax
Here, we are taking a variable with a value as an item inside the sequence on each iteration. Loop will continue until we reach the last item in the series.
Let’s take an example of a simple for loops python.
The output of for loop
We can also use a for loop with String using the following method.
Example of for loop using string.
The output of the above program.
Example of the addition of the list using for loop
When we run this program, the loop will take each item in the list in the val variable and then make an addition with the variable sum until the sequence is completed.
Nested for loop in python
We can also add multiple loops inside a loop.
Syntax of nested for loop
Let see an example of a nested loop.
The output of nested for loops python.
for loop with else statement in python
We can also use an else statement in for loop just like if conditional statement. The else part is executed if the items in the sequence used in for loop exhausts.
Syntax of for loop with else
Example of for loop with else statement
When we run the program, we get the following output:
As you can see, the program prints all the items in the list, and once the last item is printed and for loop has no sequence to execute, it will exit from the loop, and the else statements we executed.