Python Loops – Things You MUST Know about Loops in Python

  • We can create loops in Python using for loop and while loop.
  • The for loop is used to iterate over a collection of items such as Tuple, List, Set, Dictionary, String, etc.
  • Python for loop is always used with the “in” operator.
  • The while loop is used to execute a block of code until the specified condition becomes False.
  • Python has two loop control statements – break and continue.
  • Python also supports nested loops.
  • We can use “else” block with for loop and while loop to execute a block of code if the loop terminates naturally.

Python Loops Syntax

1. for loop syntax

for element in sequence:
    # for statement code block
else: # optional
    # else block code

2. while loop syntax

while condition:
    # while block code
else: # optional
    # else block code

Python for loop Examples

Let’s look at a simple example of for loop to iterate over a sequence, collection, and dictionary items.

1. Looping over String Characters

>>> str = "Python"
>>> for c in str:
...     print(c)
... 
P
y
t
h
o
n
>>> 

2. Looping over a Tuple Elements

>>> t = (1,2,3)
>>> for i in t:
...     print(i)
... 
1
2
3
>>>

3. Looping over a List Elements

>>> fruits = ["Apple", "Banana", "Grapes"]
>>> 
>>> for fruit in fruits:
...     print(fruit)
... 
Apple
Banana
Grapes
>>> 

4. Looping over a Set Elements

>>> my_set = set("ABCBA")
>>> 
>>> for c in my_set:
...     print(c)
... 
C
B
A
>>> 

Note that the Set is an unordered sequence, so the output might be different if you run the same code snippet.


5. Looping over a Dictionary Items

We can use dictionary items() method to get the view of the dictionary items. Then unpack them to comma-separated values in the for loop.

>>> num_dict = {1: "one", 2: "two", 3: "three"}
>>> 
>>> for k, v in num_dict.items():
...     print(f'{k}={v}')
... 
1=one
2=two
3=three
>>>

Python while loop Examples

Let’s look at some examples of using while loop in Python.

1. Looping fixed number of times

Let’s say we have to run a block of code for 5 times. We can use while loop to write this loop.

>>> count = 5
>>> 
>>> while count > 0:
...     print("run this code")
...     count -=1
... 
run this code
run this code
run this code
run this code
run this code
>>>

2. Looping random number of times

from random import Random


def change_count():
    global count
    r = Random()
    count = r.randint(0, 12)


count = 0
while count < 10:
    print("print this random times")
    change_count()

Here we are using Random class to change the value of count. So the while loop will run for a random number of times.


Using else statement with loops

We can use else statement with both for-loop and while-loop.

1. else with for loop

for i in (1, 2):
    pass
else:
    print("1. for loop executed successfully")

for i in (1, 2):
    try:
        raise ValueError
    except ValueError as ve:
        pass
else:
    print("2. for loop executed successfully")

try:
    for i in (1, 2):
        raise ValueError
    else:
        print("3. for loop executed successfully")
except ValueError as ve:
    print("4. ValueError Raised.")
Loops In Python
Loops In Python

Notice that when the exception is raised in the for loop and it’s not handled, the else block code is not executed. This behavior is the same in case of while loop also.


2. else with the while loop

count = 0
while count < 5:
    pass
    count += 1
else:
    print("1. else block code")

count = 0
try:
    while count < 5:
        raise ValueError
        count += 1
    else:
        print("2. else block code")
except ValueError as ve:
    print("3. except block")

Output:

Python while loop with else block
Python while loop with else block

Python loop control statements

Python has two loop control statements.

  1. break
  2. continue

1. break statement in loops

ints = [1, 2, 3, 5, 4, 2]

for i in ints:
    if i > 4:
        break
    print(i)
Python Loop Control Statement Break
Python Loop Control Statement – break

2. continue statement in loops

def process_even_ints(ints_list):
    for i in ints_list:
        if i % 2 != 0:
            continue
        print("Processing", i)


process_even_ints([1, 2, 3, 4, 5])

Output:

Python Loop Control Statement Continue
Python Loop Control Statement – continue

Nested Loops in Python

We can have any level of nested loops in Python. We can use for-loop as well as while loop to create nested loops.

Here is a simple example to print the elements of a nested list using the nested loops.

nested_sequence = ["01", (2, 3), [4, 5, 6]]

for x in nested_sequence:
    for y in x:
        print(y)
Nested Loops In Python
Nested Loops In Python

Conclusion

Python for loop and while loops are enough to create any type of loops. We can use the break and continue statements to control the loop execution flow. You can also use the “else” block for logging successful execution of the loops.


References: