Home
About Us Privacy Policy
 

LOOPS IN PYTHON

ADVERTISEMENT

Intermediate Loops



What are looping structures, and what purpose do they serve?

In Python, looping structures are statements used to execute statements repeatedly. Before delving into Python code, let us take a real-world example of when you were in school and did something naughty. Your teacher instructed you to do your homework multiple times, and you had to oblige. Loops in Python work the same way; they repeat statements given by the programmer for (in)finite repetitions.

Loops repeat statements for (in)finite repetitions.

Types of looping structures available in Python

Python provides two types of looping structures as follows:

  • The for statement
  • The while statement

The for statement

The for statement in Python iterates over a sequence of values. The sequence can be a string, an iterator, list, tuple, dictionary. Much of these will be covered later. We'll iterate over strings and get acquainted with the range() method for now.

Syntax:

for <identifier 1, identifier 2> in <sequence_types>:
    statement 1
    statement 2 
    ...
    ...
    ...
    statement N


Example of iterating over a string:

# To iterate over a string
# and print all the characters in it.
my_name = "James Bond"
for e in my_name:
    print(e, end="")
print()   # Print a newline

James Bond


The range() method

We can iterate over by using the range() method to generate a number(s).

Syntax:

range(start_index, end_index, step)


Let us discuss the components:

start_index is an integer number specifying at what index to start. It is Optional.

end_index is an integer number specifying at what index to end. It is Optional. Always remember, the last index would not be accessed. For example, range(0, 5) would produce 0, 1, 2, 3, 4, but not 5.

step is an integer number specifying by what to increment. Default is by a count of 1.

# Example
# Iterate over range method
# This loop will begin from 0 and end at 4
for i in range(0, 5):
    print(i)

0
1
2
3
4


Iterate over a range with a step

# Example
# Printing only even numbers till 10
for i in range(0, 10, 2):
    print(i)

0
2
4
6
8


ADVERTISEMENT

The while statement

The while statement is using to repeat the execution of statements until the condition becomes false. Such loops are more common on device drivers where the device is continuously searching to process data.

Syntax:

while <condition>:
    statement 1
    statement 2 
    ...
    ...
    ...
    statement N
            

Examples:

Printing numbers from 1 to 10

# Printing numbers from 1 to 10
i = 1
while i <= 10:
    print(i)
    i += 1

1
2
3
4
5
6
7
8
9
10

Printing even number from 1 to 10

# Printing even number from 1 to 10
i = 0
while i <= 10:
    if i % 2 == 0 :
        print(i)
    i += 1

Whenever using a while loop, always remember to update; otherwise, it will become an infinite loop.


ADVERTISEMENT

The break statement

The break statement in the Python programming language is used to exit the loop after a defined condition evaluates to True. For example, suppose you want to exit the loop printing number 1 to 10; if the number is greater than 5, here is how you would use the break statement.

# Printing number 1 to 10
for i in range(1, 11):
    if i > 5:
        break
    else:
        print(i)

1
2
3
4
5

Notice, the end_range is 11. Hence, the numbers would iterate to 10.


The continue statement

The continue statement is used to stop any further execution and reset the loop to start executing from the first statement defined within the loop.

Suppose you want to skip all odd numbers and print only even numbers. Here is how you would do it.

Example:

# Skip all odd numbers
for i in range(0, 11):
    if i % 2 == 1:
        continue
    else:
        print(i)

0
2
4
6
8
10


Infinite Loop

Infinite loops are loops that do not have any exit mechanism. These loops execute till the duration of the program. Such loops are customary in Device Drivers, PIC (Programmable Interrupt Controller), threads, etc.

You can use the while statement to create an infinite loop.

Syntax:

while <true condition>:
    statement 1
    statement 2
    ...
    ...
    ...
    statement N
                

Example

while True:
    print("Press CTRL + Z to exit")

Press CTRL + Z to exit
Press CTRL + Z to exit
Press CTRL + Z to exit
Press CTRL + Z to exit
Press CTRL + Z to exit
Press CTRL + Z to exit


Nested Loops

Nested loops are loops that contain a Looping structure within a loop.

Example:

# Printing multiplication table till 10

for i in range(1, 11):
    print(f"Printing table of {i}\n")
    j = 1
    while j <= 10:
        print(i * j)
        j += 1
    print("\n")

Printing table of 1

1
2
3
4
5
6
7
8
9
10


Printing table of 2

2
4
6
8
10
12
14
16
18
20


Printing table of 3

3
6
9
12
15
18
21
24
27
30


Printing table of 4

4
8
12
16
20
24
28
32
36
40


Printing table of 5

5
10
15
20
25
30
35
40
45
50


Printing table of 6

6
12
18
24
30
36
42
48
54
60


Printing table of 7

7
14
21
28
35
42
49
56
63
70


Printing table of 8

8
16
24
32
40
48
56
64
72
80


Printing table of 9

9
18
27
36
45
54
63
72
81
90


Printing table of 10

10
20
30
40
50
60
70
80
90
100


ADVERTISEMENT

Conclusion

In this chapter, we learned about looping structures in Python and discussed their purpose, the different types of looping structures available, the break and continue statement to exit and restart the iteration.

We also learned the advantages/disadvantages of using the for-loop and the while-loop, creating infinite and nested loops.


ADVERTISEMENT



All product names, logos, and brands are property of their respective owners.