Mastering the Use of ‘For’ and ‘While’ Loops in Python

Featured Image

Hello Everyone! Today we have another exciting topic of discussion, and that is When to use the 'while' or 'for' loop in Python.

In this article, we will explore Python’s 'for' loop and ‘while’ loop in detail with the help of an illustration.

Introduction to Python Loops

A loop can be defined as a repetition of something (usually code since we are talking about a coding language) until a particular condition is satisfied.d

There are mainly two types of loops. They’re as follows:-

  • For Loop
  • While Loop

Understanding ‘For’ Loops

In Python, the 'for' loop iterates over a sequence such as a list, tuple, string, or any iterable object.

Basic Syntax and Explanation

for iterator_var in sequence:
    statements(s)

Example: Iterating Over a List

  • As mentioned in the code above, the variable 'iterator_var' takes the value of the item inside a sequence.
  • The 'sequence' is the code block where the loop will be iterated. It can be any data type, such as String, List, and Tuple.
  • 'statement(s)' is the block of code that will be executed on each iteration of the loop.

Example Code to explore the ‘for’ loop:

Fruits = ["Apple", "Lemon", "Orange", "Strawberry"] #accessing items of the list using for loop
for var in Fruits:
      print(var)

Output

Apple
Lemon
Orange
Strawberry

This will be displayed in the console as follows:

Basic For Loop Code
Basic For Loop Code

In the above example, the 'for' loop iterates over a list of Fruits and prints each Fruit.

Break Statement in ‘for’ Loop

When the 'break' statement is used, it immediately exits the loop and continues with the next loop.

Here Is An Example Of For Loop Using The Break Statement:

numbers = [10,20,30,40,50,60,70,80,90,100]
for num in numbers:
     if num == 60: #print number 10 to 50 , terminating number 60
        break
     print(num)

The Output Will Be

10
20
30
40
50

Here Is An Attached Image Of The Above Code

Break Statement In For Loop 2
Break Statement In For Loop

The Range() Function

Similarly, we can use the 'range()' function to generate a sequence of numbers.

Let’s Explore the utilization of the Range() Function In the for loop:

numbers = [10,20,30,40,50,60,70,80,90,100]
for num in range(30): #generates a sequence of numbers from 0 to 29
     print(num)

The Output

#output
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

Output 3 1
Output
Output 4 1
Output 4 1

The Continue Statement

In Python, the 'continue' statement in the loop ends the current iteration and skips to the next iteration.

numbers = [10,20,30,40,50,60,70,80,90,100]
for num in range(10,101): #prints each number only if it is an even number that ie 10 to 100
      if num%2==1:
           continue
      print(num)

In this example, the list named 'numbers' contains the integer 10 to 100, inclusive. The 'range' statement will execute the number 10 to 100, inclusive, and the 'if' statement will check whether the number is even or odd using the ‘%'(modulus) Operator. If odd, the 'continue' statement will be executed.

Output

10
12
14
16
18
20
22
24
26
28
30
32
34
36
38
40
42
44
46
48
50
52
54
56
58
60
62
64
66
68
70
72
74
76
78
80
82
84
86
88
90
92
94
96
98
100

The Code Will Be Displayed As The Following:

Output 5
Output
Output 6
Output
Output 7
Output

Else Statement In For Loop In Python

The 'else' statement in a 'for' loop is executed when the loop has completed its iteration over a sequence of elements.

In This Example, The 'for' Loop Is Iterating Over The 'numbers' Lists:

numbers = [1,2,3,4,5,6,7,8]
for num in numbers:
     if num == 4:
        print(" Number 4 in the list")
        break
else: #the statement will not be executed because the loop is terminated with a 'break' statement.
     print("Number 4 not in the list")

Output:

 Number 4 in the list

So, Let’s Take A Glimpse Of The Code After The Implementation In The Console:

Else Statement In For Loop 2
Else Statement In For Loop

If Statement In For Loop In Python

In Python, a 'if' statement in a loop conditionally executes a code for each item.

Basic Example Of The If Statement:

numbers = [1,2,3,4,5,6,7,8,9,10]
for num in numbers:
    if num%2 == 0: # checks if it is divisible by 2 , using the modulo operator '%'
       print(num)

So, the output of the code is:

The code above will print all the even numbers. 
2
4
6
8
10

Here Is The Code Snippet In The Console:

If Statement In For Loop
If Statement In For Loop

Explanation:

  • The list named 'numbers' contains integers from 1 to 10.
  • The 'if' statement checks if the element is even by using the modulo operator (%).
  • If the number is even, the print statement is executed and the number is printed.

When and Why to Use ‘for’ Loop

The 'for' loop iterates over a sequence such as a list, tuple, string, or any iterable object.

However, the following are the scenarios where we can use a 'for' loop in Python:-

  • To iterate over each element of a sequence.
  • Iterate over a number range.
  • Iterate over a String, Dictionary.

Here Are Some Reasons Why We Should Use The 'for' Loop In Python:

  • Iterate over the Data Types.
  • Make code simpler.
  • Increase efficiency.

Exploring ‘While’ Loops in Python

In a 'while' loop, a set of statements that can be executed until a condition is true.

Basic Syntax and Example

while(condition):
    #Code

Here, 'condition' is the expression that will determine whether the value is 'True' or 'False' and if 'True', the code will execute to the next part. The condition will be evaluated again and if it is still 'True', the loop continues to execute. The process continues until the condition is 'False'.

We can now take a look at a Basic example exploring the application of the ‘while’ loop:

x =1
while x < 8: #will continue to execute as long as x is less than 8
    print(x)
    x += 1

The Output Will Be The Following:

1
2
3
4
5
6
7

In this example, the loop starts with ‘x’ an equal to 1, and continues executing the code till the value ‘x’ is no longer lesser than 8. When ‘x’ becomes 8, the loop no longer executes further.

Therefore, the code will execute 7 times.

While Loop Basic Example
While Loop Basic Example

Break Statement in ‘while’ Loop

Just as we have seen in 'for' loop, we will use the same procedure in the 'while' loop as well.

Example of application of Break Statement in 'while' Loop:

x=1
while x < 8: #Loop continues as long as x is less than 8
      if  x==6: #Check if x is equal to 6
            break #terminates the loop
     print(x)
     x += 1 #incrementing the value of x by 1

The Output Will Be:

1
2
3
4
5

Image Of The Code After Its Implementation Along With The Output:

Break Statement In While Loop 2
Break Statement In While Loop

Here’s an explanation of the above code:

  • Assigns value 1 to the variable 'x'.
  • Runs the 'while' loop as long as x is less than 8.
  • Evaluates whether 'x' is equal to 6.
  • If 'x' equals to 6, the loop will stop executing and break out of the iteration using the 'break' statement and if not, the loop will continue executing.
  • Increment the value of 'x' by 1.
  • The looping process repeats until the value is no longer lesser than 8.

Range() Function in ‘while’ Loop

As we have already got an idea of the 'range()' function, let us now focus on how it works in the 'while' loop.

exploring the application of the Range() Function in While Loop with an example:

x=1
while x in range(6): # iterates over the values  from 1 to 5
    print(x) 
    x += 1

Which will output:

1
2
3
4
5

Here, the 'while'loop will continue to run until the condition 'x in range(6)' is true. Hence, this will output the numbers 1 to 5 since the value of 'x' is incremented by 1 with each iteration.

Let’s take a look at the implemented code in the console:

Range Function In While Loop
Range() Function In While Loop

The Continue Statement in the ‘While’ loop

We all know that in Python, the ‘continue’ statement in the loop ends the current iteration and skips to the next iteration. Now, we are going to implement the 'continue'statement in the 'while' loop.

exploring the Application of The Continue Statement in the ‘While’ loop using an example:

i=0
while i < 7:
    i += 1
    if i==4:#skip the number 4 and move on to the next iteration
        continue
    print(i)

The Output:

1
2
3
5
6
7

Hereby, Is The Attached Image Of The Code:

Continue Statement In While Loop 2
Continue Statement In While Loop

Explanation:-

  • The code initializes a variable 'i' to 0.
  • The 'while' loop will execute until 'i' is less than 7.
  • If ‘i’ is equal to 4, the ‘continue statement will execute which will immediately make the loop skip to the next iteration.

Else Statement in ‘while’ Loop

In Python, an 'else' statement is used to determine which code block to be executed after the completion of the 'while' loop iteration.

Let’s Take A Simple Example To Illustrate The Else Statement In Detail:

i=1
while i <= 9:
    print(i)
    i += 1
else:
    print("Loop completed successfully")

This Will Output:

1
2
3
4
5
6
7
8
9
Loop completed successfully

The Attached Image:

Else Statement In While Loop 2
Else Statement In While Loop

The 'while' loop will get iterated until 'i' is less than or equal to 9. The loop will terminate and the 'else' block will be executed when 'i' reaches 10.

If Statement in ‘while’ Loop

The 'if' statement inside the 'while' loop will check a condition, and if it’s true, the specific code block will execute further.

Let’s Take A Basic Example To Comprehend The If Statement In The While Loop:

i = 1
while i <= 9:
    if i%2==0:
        print(i,"is even")
    else:
        print(i,"is odd")
    i += 1

The Output Will Be:

1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd

The Code After Implementing In The Console:

If Statement In While Loop 2
If Statement In While Loop

In this example, 'while' will execute as long as 'i' is less than or equal to 9.

The code will check whether 'x' is it even or odd to use the % (modulo) operator. If 'x' is even, the code inside the block will execute and print that the number is even or else odd.

When and Why to Use ‘while’ Loop

In Python, the 'while' loop is a set of statements that can be executed until a condition is true.

There are various situations where we can utilize the 'while' loop in Python.

For Example:-

  • When it is needed to perform an iteration until the condition is fulfilled.
  • To repeat a process a set number of times.
  • It can also be used when we do not have a piece of proper information about the execution time of a code block.

Conclusion

In Python, the for and while loops are essential for iterating over sequences and executing code blocks based on specific conditions. ‘For’ loops are ideal when you need to iterate over a known sequence, such as a list, tuple, or string. They provide simplicity and efficiency in handling data types. ‘While’ loops, on the other hand, are useful when a set of statements needs to be executed until a certain condition is met. They are suitable for situations where you don’t know how many times a code block should be executed. Mastering both types of loops helps improve your Python programming and problem-solving skills.

Reference