Python for loop is an iterator based for loop. It steps through the items of lists, tuples, strings, the keys of dictionaries and other iterables. The Python for loop starts with the keyword "for" followed by an arbitrary variable name, which will hold the values of the following sequence object, which is stepped through. The general syntax looks like this:
for <variable> in <sequence>:
<statements>
else:
<statements>
>>> languages = ["C", "C++", "Perl", "Python"]
>>> for x in languages:
... print(x)
...
C
C++
Perl
Python
>>>
The else block is special; while Perl programmer are familiar with it, it's an unknown concept to C and C++ programmers. Semantically, it works exactly as the optional else of a while loop. It will be executed only if the loop hasn't been "broken" by a break statement. So it will only be executed, after all the items of the sequence in the header have been used.
If a break statement has to be executed in the program flow of the for loop, the loop will be exited and the program flow will continue with the first statement following the for loop, if there is any at all. Usually break statements are wrapped into conditional statements, e.g.
Python for loop is an iterator based for loop. It steps through the items of lists, tuples, strings, the keys of dictionaries and other iterables. The Python for loop starts with the keyword "for" followed by an arbitrary variable name, which will hold the values of the following sequence object, which is stepped through. The general syntax looks like this:
for <variable> in <sequence>:
<statements>
else:
<statements>
>>> languages = ["C", "C++", "Perl", "Python"]
>>> for x in languages:
... print(x)
...
C
C++
Perl
Python
>>>
The else block is special; while Perl programmer are familiar with it, it's an unknown concept to C and C++ programmers. Semantically, it works exactly as the optional else of a while loop. It will be executed only if the loop hasn't been "broken" by a break statement. So it will only be executed, after all the items of the sequence in the header have been used.
If a break statement has to be executed in the program flow of the for loop, the loop will be exited and the program flow will continue with the first statement following the for loop, if there is any at all. Usually break statements are wrapped into conditional statements, e.g.
edibles = ["ham", "spam","eggs","nuts"]
for food in edibles:
if food == "spam":
print("No more spam please!")
break
print("Great, delicious " + food)
else:
print("I am so glad: No spam!")
print("Finally, I finished stuffing myself")
If we call this script, we get the following result:
$ python for.py
Great, delicious ham
No more spam please!
Finally, I finished stuffing myself
$
Removing "spam" from our list of edibles, we will gain the following output:
$ python for.py
Great, delicious ham
Great, delicious eggs
Great, delicious nuts
I am so glad: No spam!
Finally, I finished stuffing myself
$
For detailed Reference :