Loops are a very fundamental and important concept. There are two types of loops in python. They are for loop and while loop. You will learn about their use with examples. You will also learn how to use nested loops in python.
You will learn the following loops in python:
for loop
for loop is used to iterate over items in the collection. You can use for loop on strings, lists, multiple numbers as they are a collection of items.
for loop on string:
You can loop through a string as a string is a sequence of characters.
Example:
for item in 'Tutorial':
print(item)
Output:
T
u
t
o
r
i
a
l
for loop on list:
You can loop through the list as the list is a collection of items.
Example:
for item in ['John', 'Jane', 'Jack', 'Jim']:
print(item)
Output:
John
Jane
Jack
Jim
for loop on range of numbers:
You can use a loop through a range of numbers using for loop.
Example:
for item in range(1, 5):
print(item)
Output:
1
2
3
4
while loop:
while loop is used to execute a block of code several times until the condition is true.
Example:
i = 0
while i < 5:
print(i)
i = i + 1
Output:
0
1
2
3
4
Nested loop:
We can use a loop inside another loop by nesting them.
Example:
for x in range(4):
for y in range(3):
print(f'({x}, {y})')
Output:
(0, 0)
(0, 1)
(0, 2)
(1, 0)
(1, 1)
(1, 2)
(2, 0)
(2, 1)
(2, 2)
(3, 0)
(3, 1)
(3, 2)
break and continue statements in loops:
You can use the break statement to exit a for loop or a while loop.
You can use the continue statement to skip the current block.
Conclusion:
In this tutorial, you learned how to iterate over a collection of items using loops in python. You can use the following loops in python:
- for loops
- while loops
- nested loops
If you have problems while implementing code, you can ask me through the comment section.