Difference Between For Loop and While Loop in Python

In Python, the for loop and while loop are two of the basic operations used to repeat a specified action multiple times. Both loops do share similarities; however, they have distinct mechanics and applications. We generally use the for loop in case the number of iterations is known in advance, and we use the while loop for an unknown number of iterations.

What is a For Loop in Python?

The Python for loop is a programming mechanism used for iterating over a sequence until a given condition is met.

The for loop in Python allows us to iterate over iterable objects, such as tuples, lists, dictionaries, and strings, until it reaches the termination of the sequence or the condition is fulfilled. The for loop proceeds to the next step after each iteration is completed.

For Loop Syntax in Python

It has the following syntax:

for var_name in sequence:  

Parameter(s):

  • var_name: A name of a variable assigned to each element in the given sequence
  • sequence = Sequence refers to iterable elements such as lists, tuples, dictionaries, and strings
  • The loop executes once for each item in the iterable.
  • The indented block under the loop runs on every iteration.

Examples of Python For Loop

We will now look at some examples of Python ‘for’ loop:

Basic Example of a For Loop in Python

In this example, we will see a basic example of Python For Loop:

Let us see through a simple example to understand how the For Loop works:

Example

#let's  print numbers in a for loop using Range()  
for i in range(1,7): #Here we have used for loop  
    print (i)   

Output:

1
2
3
4
5
6

Explanation:

In the above example, we used a for loop with the range() function to print numbers ranging from 1 to 6.

Another Example: Use of range() with For Loop

We will now take a look at an example to understand the working of the ‘for’ loop with the range() function.

Example

#receiving the input from the users  
row = int(input("Enter number of rows: "))  
#using the range function in a For Loop  
for i in range(1, row + 1):  
    # Print spaces  
    for j in range(row - i): #nested loop used  
        print("  ", end="")  
      
    # Print stars  
    for stars in range(2 * i - 1):    
        print("* ", end="")  
      
    print()    

Output:

Enter number of rows: 5
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *

Explanation:

The above code is an example of a Nested loop, where we have printed star patterns using a Nested For Loop.

What is the While Loop?

Python is used to repeatedly execute a block of code as long as a given condition remains True. It is useful when the number of iterations is unknown beforehand.

Syntax:

while condition:    

    # code block   
    • condition: A Boolean expression that is evaluated before each iteration.
    • The code block inside the loop is executed only if the condition is true.
    • If the condition never becomes False, the loop will run infinitely, potentially causing an infinite loop.

    Examples of Python While Loop

    We will now look at some examples of Python while loops:

    Basic Example of While Loop

    In this example, we will see how the While loop functions in Python.

    Example

    # initializing a counter variable    
    counter = 0    
    # using the while loop to iterate the counter up to 5    
    while counter < 5:    
      # printing the counter value and some statement    
      print(counter, "Hello")    
      # incrementing the counter value    
      counter += 1    

    Output:

    0 Hello
    1 Hello
    2 Hello
    3 Hello
    4 Hello
    

    Explanation:

    In the above example, we have initialized a variable counter with the value 0. Then, we enter a while loop that executes the block of code as long as the counter is less than 5. Within the loop, we have printed the current value of the counter, followed by “Hello”. After each iteration, the counter is incremented by 1. Once the counter reaches 5, the condition counter < 5 becomes False, causing the loop to terminate.

    Another Example: Use of the While loop with ‘else’

    In this example, we will see how to use the While loop with the ‘else’ statement

    Example

    # initializing counter    
    i = 1    
        
    # iterate using the While loop    
    while i <= 3:    
        print(i)    
        i += 1    
        # else block    
    else:    
        print("Loop completed successfully!")    

    Output:

    1
    2
    3
    Loop completed successfully!
    

    Explanation:

    In this example, we have created a counter with an initial value of 1. We have then used the While loop with the ‘else’ statement to iterate under a specified condition. Inside this loop, we printed the counter value and increment it by 1. This loop iterates until the condition remains True. Under the ‘else’ block, we have printed a statement that runs when the condition becomes False.

    Key differences between For Loop and While Loop

    There are several differences between the for loop and the while loop in Python. Some main differences are as follows:

    Featurefor Loopwhile Loop
    DefinitionIterates over a sequence (like a list, string, or range).Repeats a block of code as long as a condition is True.
    UsageWhen the number of iterations is known or a sequence is available.When the number of iterations is unknown or depends on a condition.
    Syntaxfor variable in iterable:
    # code block
    while condition:
    # code block
    Loop ControlControlled by an iterable (e.g., list, tuple, range).Controlled by a condition that must eventually become false.
    Loop VariableAutomatically updates with each iteration.Needs to be manually updated inside the loop.
    Risk of Infinite LoopLow, since it depends on an iterable.Higher, if the condition is never made false.
    Common Use CasesIterating over items in a list, string, dictionary, etc.Waiting for user input, checking sensor data, or running until a condition.
    Structure SimplicityMore concise when working with sequences.More flexible for complex or dynamic conditions.
    TerminationEnds automatically when the iterable is exhausted.Ends only when the condition becomes false.

    Comments

    Leave a Reply

    Your email address will not be published. Required fields are marked *