Loops in python – for loop, while loop and nested loop

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 following loops in python:

  1. for loop
  2. while loop
  3. nested loop

for loop

for loop is used to iterate over items in collection. You can use for loop on strings, lists, multiple numbers as they are collection of items.

for loop on string:

You can loop through a string as 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 list as list is 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 loop through 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 block if code several times until 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 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 collection of items using loops in python. You can use following loops in python:

  1. for loops
  2. while loops
  3. nested loops

If you have problems while implementing code, you can ask me through the comment section.

See Also:

Strings in python

Variables in python

Leave a Reply

Your email address will not be published. Required fields are marked *