for Loop:
- use to iterate over a sequence (like a list, tuple, string, or range) and execute a block of code multiple times, once for each item in the sequence.
Basic Syntax:
for variable in sequence:
# Code to execute for each item in the sequence
Example:
Iterating Over a List:
- In the below example, the loop iterates over each item in the SAARC_Country list, and the country takes on the value of each item in the list during each iteration.
SAARC_Country = ["Bangladesh", "India", "Pakistan","Nepal","Bhutan","Afghanistan","Maldives","Sri-Lanka"]
for country in SAARC_Country:
print(country)
Output: Bangladesh India Pakistan Nepal Bhutan Afghanistan Maldives Sri-Lanka
Using range():
- The range() function generates a sequence of numbers, often used with loops to repeat a block of code a specific number of times.
- In the example below, range(10) generates the numbers 0 to 9, and the loop prints each number.
for i in range(10):
print(i)
Output: 0 1 2 3 4 5 6 7 8 9
Iterating Over a String:
- We can use a for loop to iterate over the characters in a string
for name in "Masud Rana":
print(name)
Output: M a s u d R a n a
Nested for Loops:
- We can nest for loops to iterate over multi-dimensional sequences (like lists of lists).
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
for row in matrix:
for item in row:
print(item)
Output: 1 2 3 4 5 6 7 8 9
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
for row in matrix:
for item in row:
print(item, end=" ") #end=" " is used to keep the output of each row on the same line with a space
separating each item.
print()
Output: 1 2 3 4 5 6 7 8 9
The break Statement:
- If we want to stop the loop before it loop through all items, we can use ‘break” statement
SAARC_Country = ["Bangladesh", "India", "Pakistan","Nepal","Bhutan","Afghanistan","Maldives","Sri-Lanka"]
for country in SAARC_Country:
print(country)
if country== 'Bhutan':
break
Output: Bangladesh India Pakistan Nepal Bhutan
The continue Statement:
- With the continue statement, we can stop the current iteration of the loop, and continue with the next item
SAARC_Country = ["Bangladesh", "India", "Pakistan","Nepal","Bhutan","Afghanistan","Maldives","Sri-Lanka"]
for country in SAARC_Country:
if country== 'Bhutan':
continue
print(country)
Output: Bangladesh India Pakistan Nepal Afghanistan Maldives Sri-Lanka