Loop Control Statements in Python with Examples

What are Loops in Python?

In Python, loops are used to do the same thing over and over until a certain condition is met. To elaborate on the topic, we will learn about loops in Python Programming, including the different types of loops like For loops, While loops, and Nested loops with diagrams and examples. We will also talk about the different kinds of control statements in Python and how they work with loops.

In general, Loops statements are executed in order. For example, the first statement in a function is executed first, then the second, and so on. There may be times when you need to execute a block of code multiple times.

A loop statement allows a statement or set of statements to be run more than once. The diagram below is the structure of a loop statement:

Structure of loop statement
Structure of loop statement

Why we use Loop in Python

The reason why we use loops in Python is that loops are essential in any programming language because they allow you to repeatedly execute a section of code. You will frequently encounter circumstances in which you need to reuse a piece of code, but you do not want to write the same line of code many times.

Different Types of Loops in Python

The following is a list of the different types of loops in Python:

Python Tutorial 11 - Loop Control S...
Python Tutorial 11 - Loop Control Statements and Iterator - Break Continue Pass
  • For Loops
  • While Loops
  • Nested Loops

For Loops in Python

This is more like the iterator function in other object-oriented programming languages than the for keyword in other languages.

We can execute a sequence of statements once for each item in a list, tuple, set, etc. using the for loop.

For Loops Syntax

The following code below is the for loops syntax in Python:

for iterating_var in sequence:
    #execute your code

For Loops Flow Diagram

Below is the for loops flow diagram:

For Loops Flow Diagram in Python
For Loops Flow Diagram

For Loops Examples

Here is a for loops examples:

months = ["Jan", "Feb", "Mar"]
for a in months:
    print(a)

Output:

Jan
Feb
Mar

The for loop doesn’t need you to set up an indexing variable first.

Even strings, which are made up of a series of characters, are iterable objects.

for a in "itsourcecode":
  print(a)

Output:

i
t
s
o
u
r
c
e
c
o
d
e

Else Statements in For Loops

Like if statements, a for loop can have an optional else statement block. If there are no more items in the order used in the for loop, the else part is executed.

A for loop can be stopped with the break keyword. When this happens, the else part is ignored.

So, the else part of a for loop runs if there is no break.

Example:

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

for i in count:
    print(i)
else:
    print("No items left.")

Output:

5
4
3
2
1
No items left.

While Loops in Python

A while loop statement in Python programming runs a target statement over and over as long as a given condition is true.

Most of the time, we use this loop when we don’t know ahead of time how many times to iterate.

While Loops Syntax

The following code below is the while loops syntax in Python:

while expression:
    #execute your code

While Loops Flow Diagram

Below is the while loops flow diagram:

While Loops Flow Diagram in Python
While Loops Flow Diagram

While Loops Examples

Here is a while loop example:

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

Output:

1
2
3
4
5
6
7
8
9
10

Don’t forget to increment i or the loop will keep going forever.

In order to use the while loop, the right variables must be ready. In this case, we need to define an indexing variable iand set it to 1.

Else Statement in While Loops

We can also use the else statement in while loops in Python just like in for loops.

A break statement can be used to end the while loop. In these situations, the else part is ignored. So, the else statements part of a while loop runs if the condition is false and there is no break.

Example:

count = 0
while count < 5:
   print (count, " is  less than 5")
   count = count + 1
else:
   print (count, " is not less than 5")

Output:

0  is  less than 5
1  is  less than 5
2  is  less than 5
3  is  less than 5
4  is  less than 5
5  is not less than 5

Nested Loops in Python

A nested loops in Python is a loop that is inside the body of another loop. This means that every time the “outer loop” is run, the “inner loop” will be run once.

Nested Loops Syntax

Below is the nested loop syntax in Python:

for iterating_var in sequence:
    for iterating_var in sequence:
       #execute your code
          #execute your code

Nested Loops Flow Diagram

The following figure below is the nested loops flow diagram.

Nested Loop Flow Diagram in Python
Nested Loops Flow Diagram

Python Nested Loops Example

Below is the Nested Loops Example in Python:

color = ["red", "blue", "yellow"]
thing = ["cellphone", "laptop", "shoe"]

for a in color:
  for b in thing:
    print(a, b)

Output:

red cellphone
red laptop
red shoe
blue cellphone
blue laptop
blue shoe
yellow cellphone
yellow laptop
yellow shoe

Loop Control Statements in Python

Loop Control Statements in Python are used to alter the execution flow. These may be used to skip an iteration or terminate the process.

Types of Loop Control Statements

Below are the different types of loop control statements in Python:

  1. Break Statement
  2. Continue Statement
  3. Pass Statement

Break Statement

Depending on the specified circumstance, the break statement halts execution and exits the loop.

Example: Make a list of odd numbers between 1 and 20. (use while, break)

num = 1
odd_nums = []
while num:
    if num % 2 != 0:
        odd_nums.append(num)
    if num >=20:
        break
    num += 1
print("Odd numbers: ", odd_nums)

Output:

Odd numbers:  [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

Continue Statement

When the condition is met, the continue statement skips the current iteration and lets the loop move on to the next one. It doesn’t take control out of the loop unless you put the break statement outside of the loop.

Example: If the current number is 6, skip the iteration (use while, continue)

num = 0
while num < 10:
    num += 1
    if num == 6:
        continue
    print(num)

Output:

1
2
3
4
5
7
8
9
10

Pass Statement

The pass statement is used in Python when a statement is required syntactically but no command or code is to be run. It doesn’t skip over or stop the execution. Instead, it moves on to the next iteration.

It’s useful when we don’t want to write code right now but want to add functionality later.

Example:

#while loop pass statement
print("While loop Pass Statement\n")
num = 1
while num <= 10:
    if num == 6:
        pass
    print(num)   
    num += 1

print("\nFor loop Pass Statement\n")
#for loop pass statement
for num in range(1, 11):
    if num == 6:
        pass
    print(num)

Output:

While loop Pass Statement

1
2
3
4
5
6
7
8
9
10

For loop Pass Statement

1
2
3
4
5
6
7
8
9
10

Summary

In summary, you learned about the different types of loops in Python. I hope this tutorial helped you figure out how to use Python loops.

Now that you know what Loops are, you are one step closer to writing better, more powerful code. Start putting all the loops you’ve learned about today into your code.

In the next post, “Python Numbers,” you’ll learn about how to use numbers and the different types of numbers in Python.


Leave a Comment