There are only two options in Python for Iterative Processing.
1. while loop
2. for loop
When the number of interation are not known upfront, use while loop.
while <expression> :
while loop Examples:
a,b = 0,1 while b < 50: print(b) a,b = b, a+b print("done") #look at the indentation
while True: #infinite loop
a = 10 while True: a -= 2 print(a) if (a < 1): break
iterable – is any data structure that supports element traversal ex: stings, lists, tuples
iterators, lines of file, keys of dict,generator sets etc.
In Python we can use for loop in two styles.
for element in iterable:
#do something with element
Here element is just a variable, and iterable can be list, tuple, strings etc …
This is useful when, iterating through one iterable object.
item_list = ['item 0', 'item 1', 'item 2', 'item 3', 'item 4'] for item in item_list: print(item)
for i in range (start, end, step):
#do something with i
range() is a built in function, Return an object that produces a sequence of integers.
Here is i is a varible holds return value of range object.
This style is useful when iterating through multiple iterabe object.
item_list = ['item 0', 'item 1', 'item 2', 'item 3', 'item 4'] value_list = ['value 0', 'value 1', 'value 2', 'value 3', 'value 4'] for i in range(0, len(item_list)): #using i as index for both lists print(item_list [i], value_list[i])
Lets look at some more for loop examples.
for num in range(10): print(num) for num in range(5,25): print(num) for num in range(5,25,2): print(num)
Using enumerate() built in function with for loop.
enumerate(iterable[, start]) -> iterator for index, value of iterable
Return an enumerate object. iterable must be another object that supports iteration.
music =('rock','pop','alternative','folk') for i in range(len(music), 1): print('music : %d: %s' %(i, music[i])) for i, style in enumerate(music,1): print ("music %d : %s " %(i, style)))
fd = open('lines.txt') for line in fd.readlines(): print(line)
Example of 2D arrays.
2 dimensional arrays are presented as list of lists in Python.
each row is a inner list. suppose we have first row
2,5,3,5,7 and second row as 1,2,4,5,8.
A 2D array of these two rows represented as below.
2D array traversal using for loop
Below example shows, how to access or iterate through 2D arrays.
a = [[2,5,3,5,7], [1,2,4,5,8]] #method 1 print("#### methods 1 ####:") for row in a: for item in row: print(item) print("#### methods 2 #### :") for i in range(len(a)): for j in range(len(a[i])): print(a[i][j])
break – Break stops the current loop execution.
continue – skips current execution and moves on to the next cycle.
pass – means do nothing.
a = 5 if a >= 10: pass else: print("'a' is less than 10")