Python Data Persistence – for Keyword

Python Data Persistence – for Keyword

Like many other languages, Python also provides for keywords to construct a loop. However, Python’s for loop is a little different from others. Instead of a count-based looping mechanism, Python’s for loop iterates over each item in a collection object such as list, tuple, and so on.
Python’s sequence-type objects are the collections of items. These objects have an in-built iterator. An iterator is a stream that serves one object at a time until it is exhausted. Such objects are also called iterable. Python’s for loop processes one constituent of an iterable at a time till it is exhausted. The general form of usage of for statement is as follows:

Example

#using for loop
for obj in iterable:
#for block
#processing instructions of each object
. . .
end of block

Unlike the while loop, any other Boolean expression is not required to control the repetition of this block. Let us take a simple example. If you want to calculate the square of each number in a list, use for loop as shown below:

Example

#for-1.py
numbers=[4,7,2,5,8]
for num in numbers:
sqr=num*num
print ( ' sqaure of { } is { } ' . format ( num , sqr ) )

Output:

E:\python3 7 >python for-1.py 
square of 4 is 16 
square of 7 is 49 
square of 2 is 4 
square of 5 is 25 
square of 8 is 64 

E:\python37 >

Just like a list, a tuple or string object is also iterable. The following code snippet uses a for loop to traverse the characters in a sentence and count the number of words in it assuming that a single space (‘ ‘)separates them.

Example

#for-2.py
sentence=1 Simple is better than complex and Complex is. better than complicated. '
wordcount=1
for char in sentence:
if char==' ':
wordcount=wordcount+1
print ('the sentence has { } words'.
format(wordcount))

Output

E:\python37>python for-2.py 
the sentence has 11 words 

E:\python37>