In programming a loop is a structure that repeats a sequence of instructions until a specific condition is met. It is used to iterate over a sequence (list, tuple, string) or other iterable objects. Iterating over a sequence is called traversal.
For loop
for loops iterate over a collection of items and run a block of code with each element from the collection.
numbers_list = [1, 2, 3, 4, 5]
for i in numbers_list:
print(i)
The above for loop iterates over a list named numbers_list. Each iteration sets the value of i
to the next element of the list. So first it will be 1, then 2 etc. The output will be as follow:
range
is a function that returns a series of numbers under an iterable form-
for i in range(5):
print(i)
gives the exact same result as the first for loop. 5 is not printed as the range here is the first five numbers starting from 0.
To iterate through a list you can use for :
animal_list = ['Cat', 'Dog', 'Cow', 'Fox', 'Tiger', 'Lion']
for animal in animal_list:
print(animal)
The same result can be obtained using range-
for animal in range(len(animal_list)):
print(animal_list[animal])
The len() is a built-in function returns the number of items in an object.
If you want to loop through both the elements and the index for the elements, you can use Python’s enumerate function:
for index, item in enumerate(animal_list):
print(index, ':', item)
enumerate will generate tuples, which are unpacked into index and item
(the actual value from the list). The above loop will print
To iterate through a dictionary you can use for :
Considering the following dictionary and to iterate through its keys, you can use:
customer = {'Name': 'Anna', 'Mobile': '12345678', 'Age': 23, 'City': 'Dhaka'}
for key in customer:
print(key)v
Output:
This is equivalent to :
for key in customer.keys():
print(key)
To iterate through its keys and values, use:
for key, value in customer.items():
print(key, ' : ', value)
Output:
While Loop
A while loop will cause the loop statements to be executed till the loop condition remains true . The following code will execute the loop statements a total of 4 times-
i = 0
while i < 4:
i = i + 1
while
loops are useful for checking if some condition has been met. The following loop will continue to execute until myObject
is ready.
myObject = anObject()
while myObject.IsNotReady():
myObject.TrytoGetReady()
If the condition is always true the while loop will run forever (infinite loop), if it is not terminated by a break or return statement or an exception.
while True:
print(10)
Python doesn’t have a do or a do-while loop (this will allow code to be executed once before the condition is tested). However, you can combine a while True with a break to achieve the same purpose.
a = 20
while True:
a = a-2
print(a)
if a<10:
break
print('Done.')
This will show:
If you want to loop over a list of tuples for example:
collection = [('a', 'b', 'c'), ('x', 'y', 'z'), ('1', '2', '3')]
Instead of doing this:
for item in collection:
i1 = item[0]
i2 = item[1]
i3 = item[2]
# logic
You can simply do-
for i1, i2, i3 in collection:
# logic
This will also work for most types of iterables, not just tuples.
Break and Continue in Loops
When a break statement executes inside a loop, control flow “breaks” out of the loop immediately:
i = 0
while i < 7:
print(i)
if i == 4:
print("Breaking from loop")
break
i += 1
The loop conditional will not be evaluated after the break statement is executed.
break statements can also be used inside for loops.
A continue statement will skip to the next iteration of the loop but continuing the loop. As with break, continue can only appear inside loops:
for i in (0, 1, 2, 3, 4, 5):
if i == 2 or i == 4:
continue
print(i)
Output:
Note that 2 and 4 aren’t printed, this is because continue goes to the next iteration instead of continuing when i ==2 or i == 4 occurred.
You can use return statement as a break ( note that any code after return will not be executed either)-
def break_loop():
for i in range(1, 5):
if i == 2:
return i
print(i)
return 5
break_loop()Output: 1
Pass Statement
pass is a null statement for when a statement is required by Python syntax , but no action is required or desired by the programmer. This can be useful for code that is yet to be written.
for x in range(10):
pass #we don't want to do anything right now , so we'll pass