We have discussed about
while Statement in our previous Article “Python – Control Flows – The while Statement“. The
while Statement is useful to repeatedly execute the statements as long as the conditional expression evaluates to true. In this article, we are going to discuss another compound statement, the
for Statement in Python is used to iterate the elements in the sequence. It also works with the objects that have iteration support. If you attempt to use
for loop with the objects those do not support iteration, Python will throw the Error. Here is the example.
>>> a = 20 >>> for i in a: ... print(i) ... Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not iterable
In the below example, we will use
for loop to iterate through each element in the list and display the element.
>>> l = ["C/C++", "Java", "Python"] >>> for e in l: ... print(e) ... C/C++ Java Python >>>
Observe that, you no need to worry about the bounds of the list;
for loop automatically takes care of this. If you use it,
while Statement with sequences, you must consider the bounds of the sequences in order to access the elements.
We will discuss more topics in my upcoming Articles.