Loops

Loops are a key component of Python, allowing for the repeated execution of specific pieces of code. From simple iteration through lists to performing complex data operations, loops provide efficient and flexible solutions to a wide range of problems. In Python, the two main loops, ‘for‘ and ‘while‘, have their own unique uses, and understanding how they work and how to use them properly is the foundation for writing optimal and clear code.

The ‘for’ loop

The ‘for‘ loop in Python is used to iterate through the elements of a sequence or other iterable objects. The loop continues until all of the elements in the sequence have been processed, at which point the program moves on to the next line of code after the ‘for‘ loop block.

The syntax of the ‘for‘ loop is quite simple and easy to understand:

for variable in sequence:
      block of code
      ...

Where:

variable – represents the name of a variable that is used to store the current value of one of the elements in the sequence when the loop iterates,

sequence – is an iterable object that the loop will iterate over,

block of code – is the set of instructions to be executed for each element in the sequence.

Example:

for n in range(1, 5):
    print(f'2 to the power of {n} is {2**n}')

Result of the above code:

2 to the power of 1 is 2
2 to the power of 2 is 4
2 to the power of 3 is 8
2 to the power of 4 is 16

The ‘range(start, stop [,step])‘ function creates an object representing a range of integers with values from ‘start‘ upwards, but not including ‘stop‘. If the ‘start’ value is not specified, it is assumed to be zero by default. In addition, you can specify the optional iteration step ‘step‘ as the function’s third argument.

Here are a few examples:

a = range(4)                #a=0,1,2,3
b = range(1, 7)            #b=1,2,3,4,5,6
c = range(0, 14, 3)     #c=0,3,6,9,12
d = range(7, 1, -1)      #d=7,6,5,4,3,2

The ‘for‘ loop in Python is not limited to integer sequences. It can be used to iterate over various types of objects, such as strings, lists, dictionaries, or files. Here are some examples:

Example – displaying individual message characters:

message = 'Hello World'
for c in message:
    print(c)

Result of the above code:

H
e
l
l
o
 
W
o
r
l
d

Example – displaying list items:

names = ['Dave', 'Mark', 'Ann', 'Phil']
for name in names:
    print(name)

Result of the above code:

Dave
Mark
Ann
Phil

Example – displaying all dictionary items:

prices = {'GOOG': 490.10, 'IBM': 91.50, 'AAPL': 123.15}
for key in prices:
    print(key, '=', prices[key])

Result of the above code:

GOOG = 490.1
IBM = 91.5
AAPL = 123.15

Example – displaying all lines in the foo.txt file:

with open('foo.txt') as file:
    for line in file:
        print(line, end='')

Result of the above code, in my case, was that the foo.txt file contained 4 lines of such text:

1. njVFuNgdXB7aNI80Xs2785VmiHff2
2. JR1lztn0VJ1MI7ywffwRCuChzJOPL
3. 652yojVoOy3jUpHkNsHwE2djzlGmF
4. 9Muc0jDUmIJLh2WcLnvwCLPmJEpDV

The ‘while’ loop

The ‘while‘ loop in Python is used to execute a block of statements as long as the condition is true.

The syntax of the ‘while‘ loop is as follows

while condition:
      block of code
      ...

Where ‘condition‘ is a logical expression that is checked before each iteration of the loop. If the condition is True, the loop continues to execute. If the condition becomes False, the execution of the loop is terminated and the program moves to the next block of code outside the loop.

Example:

i = 0

while i < 5:
    print(i)
    i += 1

Result of the above code:

0
1
2
3
4

In this example, the ‘while‘ loop is executed as long as ‘i‘ is less than 5. Each iteration of the loop will increment ‘i‘ by 1.

The ‘break’ statement

The ‘break‘ statement in Python is used to immediately stop the execution of a loop, regardless of whether it is a ‘for‘ or ‘while‘ loop. After the ‘break‘ statement is executed, the program resumes execution from the first statement outside the loop.

The syntax of the ‘break‘ command is as follows:

break

An example of using the ‘break‘ statement in a ‘for‘ loop:

for i in range(5):
    if i == 3:
        break
    print(i)

Result of the above code:

0
1
2

In this example, the ‘for‘ loop will iterate through a sequence of numbers from 0 to 4 generated by the ‘range(5)‘ function. On each iteration, the variable ‘i‘ will take the next value from this sequence. When ‘i‘ reaches the value 3, the conditional statement ‘if i == 3‘ is satisfied, causing the ‘break‘ statement to be executed. The ‘break‘ statement will immediately break the ‘for‘ loop, which means that the loop will not continue iterating for ‘i = 4‘ and will not execute any more statements within the loop block.

An example of using the ‘break‘ statement in a ‘while‘ loop:

i = 0

while True:
    print(i)
    i += 1
    if i > 5:
        break

Result of the above code:

0
1
2
3
4
5

In this example, the ‘while‘ loop starts with a ‘true‘ condition, which means that it will run indefinitely until it encounters a ‘break‘ statement. At each iteration of the loop, the program first prints the value of the variable ‘i‘ and then increments it by 1. When the value of ‘i‘ exceeds 5, the condition ‘if i > 5‘ becomes true, which activates the ‘break‘ statement. As a result, the loop stops.

The ‘continue’ statement

The ‘continue‘ statement in Python is used in ‘for‘ or ‘while‘ loops to skip the current iteration of the loop and continue with the next iteration. When the ‘continue‘ statement is encountered, all remaining code in the current iteration of the loop is skipped, and the loop continues to check the loop condition (in the case of a ‘while‘ loop) or continues to the next value in the sequence (in the case of a ‘for‘ loop).

The syntax of the ‘continue‘ statement is as follows:

continue

An example of using the ‘continue‘ statement in a ‘for‘ loop:

for i in range(10):
    if i % 2 == 0:
        continue
    print(i)

Result of the above code:

1
3
5
7
9

In this example, the ‘for‘ loop iterates through the numbers from 0 to 9 (created by the ‘range(10)‘ function). For each number, the loop checks if the number is even (that is, if the remainder of the division by 2 is 0, checked by ‘i % 2 == 0‘). If the number is even, the ‘continue‘ statement is executed, skipping the rest of the code in the current iteration of the loop and moving on to the next iteration. As a result, ‘print(i)‘ is only executed for odd numbers.

An example of using the ‘continue‘ statement in a ‘while‘ loop:

i = 0

while i < 10:
    if i % 2 != 0:
        i += 1
        continue
    print(i)
    i += 1

Result of the above code:

0
2
4
6
8

In this example, the ‘while‘ loop runs as long as the value of the variable ‘i‘ is less than 10. The loop checks if ‘i‘ is an odd number (checking that the remainder of dividing ‘i‘ by 2 is not 0). If ‘i‘ is odd, the ‘continue‘ statement is called, which skips the rest of the code in this iteration and continues the loop with the next value of ‘i‘. However, before ‘continue‘ occurs, the value of ‘i‘ is incremented by 1 to avoid an infinite loop. For even numbers, the code in ‘if‘ is skipped and ‘print(i)‘ prints the number. As a result, the program prints only even numbers from 0 to 8, since odd numbers are skipped by the loop.

Zbigniew Marcinkowski - IamZIBI.com

Zbigniew Marcinkowski

My name is Zbigniew, but you can call me ZiBi. I have been fascinated by technology since my childhood. At that time I tended to break things rather than fix them. Everything changed when I got my first computer. I found my passion, which has stayed with me through good times and bad. You can read more about this on the "About me" page.

Leave a Comment