Loops in Python: Exploring For, While, and Nested Loops

What are Loops in Python?

  • Loops are used to do the same thing over and over until a certain condition is met.
  • Loops are programming constructs that allow you to repeatedly execute a block of code based on a certain condition.
  • Loops are used to automate repetitive tasks and iterate over collections of data.

The diagram below is the structure of a loop statement:

Structure of loop statement
Structure of loop statement

Why do we use Loop in Python?

The reason why we use loops in Python is that loops are essential in any programming language since 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.

Types of Loops in Python

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

  • For Loops
  • While Loops
  • Nested Loops

1. For Loops in Python

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

Syntax

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

for iterating_var in sequence:
    #execute your code

Flow Diagram

Below is the for loops flow diagram:

For Loops Flow Diagram in Python
For Loops Flow Diagram

Examples

Here are some of for loops examples:

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

You can test the above example here! ➡Python Online Compiler

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.")

You can test the above example here! ➡Python Online Compiler

Output:
5
4
3
2
1
No items left.

2. 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.

Syntax:

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

while expression:
    #execute your code

Flow Diagram

Below is the while loops flow diagram:

While Loops Flow Diagram in Python
While Loops Flow Diagram

Examples

Here is a while loop example:

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

You can test the above example here! ➡Python Online Compiler

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 i and 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")

You can test the above example here! ➡Python Online Compiler

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

3. Nested Loops in Python

A nested loop 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.

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

Flow Diagram

The following figure below is the nested loop flow diagram.

Nested Loop Flow Diagram in Python
Nested Loops Flow Diagram

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)

You can test the above example here! ➡Python Online Compiler

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

1. Break Statement

The break statement halts execution and exits the loop, depending on the specified circumstance,

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)

You can test the above example here! ➡Python Online Compiler

Output:

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

2. Continue Statement

The continue statement skips the current iteration and lets the loop move on to the next one when the condition is met.

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)

You can test the above example here! ➡Python Online Compiler

Output:

1
2
3
4
5
7
8
9
10

3. 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)

You can test the above example here! ➡Python Online Compiler

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

To conclude, this article provides a comprehensive overview of loops in Python.

It covers the concept of loops, their purpose in programming, and their ability to automate repetitive tasks.

The article explores three types of loops: for loops, while loops, and nested loops.


Leave a Comment