For loop vs while loop in Python

In this Python tutorial, I will explain what is the For loop vs while loop in Python. In the process, we will see, what is meant by Python for loop and while loop with their syntax, flow chart, and examples. And at last, we will see a tabular form of difference between for and while loop in Python.

What are loops in Python?

Loops in Python are a fundamental programming concept that allows us to repeatedly execute a block of code. They’re used when we want to run the same code multiple times, each time possibly with different values.

When writing code in Python, there are multiple ways to implement loops, but the most common are:

  • For Loop
  • While Loop

Both loops provide a way to repeatedly execute a block of code, but they do so in slightly different ways and for different reasons.

Let’s see them one by one and understand each of them:

For loop in Python

The for loop in Python is used to iterate over a sequence (such as a list, tuple, dictionary, string, or range) or any other iterable object. During each iteration, an item from the sequence is assigned to a variable, and the block of code inside the loop is executed.

The syntax of the For loop is:

for variable in sequence:
    # Code to execute for each item

Key Components:

  • variable– This is a temporary placeholder for the current item in the sequence in Python.
  • sequence– The Python sequence we want to iterate over.
  • :– Python uses indentation to define blocks of code. The colon at the end of the for statement indicates the start of this block.
  • Indented block of code– The Python code that will execute for each item in the sequence.

The Flow-chart of Python For loop:

For loop vs while loop in Python
Flow chart For loop in python

Example of for loop:

Consider a list of popular US cities:

cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]
for city in cities:
    print(city)

Output:

New York
Los Angeles
Chicago
Houston
Phoenix
for vs while loop python

This For loop in Python will print each city in the list sequentially.

READ:  How to convert a tuple to list in Python [16 different ways]

Use Cases of Python for loop:

  • Iterating through sequences (lists, strings, dictionaries, tuples, sets).
  • When the number of iterations is known in advance.

While loop in Python

The while loop in Python will execute its block of code as long as the specified condition evaluates to True. It’s essential to ensure that the condition can eventually become False, or else the loop will run indefinitely (infinite loop)

The syntax of the While loop is:

In Python, the while loop is more general than the for loop and is used to repeatedly execute a block of statements as long as a condition is True. The syntax is:

while condition:
    # code to execute while the condition is True

Key Components:

  • Initialization: Before the Python while loop starts, it’s common to initialize variables that will be used in the loop’s condition.
  • Condition: The loop’s condition is checked before each iteration. If the condition is True, the code inside the Python while loop is executed. If the condition is False, the loop terminates and the program proceeds to the next line of code after the loop.
  • Loop Body: This is the code that’s executed for each iteration of the while loop. It’s important to ensure that something within this Python loop body eventually changes the condition to False to prevent the loop from running indefinitely (known as an infinite loop).
  • Modification: Inside the loop body, variables involved in the loop’s condition are typically modified to ensure the condition can eventually become False.

The Flow-chart of Python While loop:

While loop flowchart in Python
Flow chart while loop

Example for while loop in Python:

Consider a typical American ritual: saving for a big purchase, like a car. If we start with $0 and save $200 every month, the months required to save up to $5000 can be calculated with Python:

savings = 0
months = 0
while savings < 5000:
    savings += 200
    months += 1
print(f"It will take {months} months to save up $5000.")

Output:

It will take 25 months to save up $5000.
while vs for loop python

The Python while loop will end when the savings will reach 5000.

Use Cases of Python for loop:

  • When the number of iterations is not known in advance.
  • To keep running a block of code until a particular condition is met or no longer holds True.
READ:  Python remove Non ASCII characters from String [7 Methods]

No condition situation in Python loops:

If no condition is specified in the for loop and while loop, the loop will iterate infinitely. In the absence of a condition, the following is the difference between while and for loop in Python:

Python For Loop:

In Python, the for loop doesn’t rely on a condition like it does in some other languages (e.g., C, C++). Instead, it iterates over the items of a sequence or other iterable objects until they are exhausted. The “condition”, so to speak, is the existence of another item in the sequence. Once there are no more items to process, the loop ends.

Still, we can create a situation where for loop in Python can go to infinite loop:

For instance, Imagine we’re given a task to print the names of all US states, but for some reason, every time we print a state’s name, we add it again to our Python list. This is, of course, a hypothetical and nonsensical scenario, but it demonstrates the concept:

states = ["California"]
for state in states:
    print(state)
    states.append(state)
  • Initially, the states Python list contained just one state: “California“.
  • The Python for loop starts and picks the first item from the list states, “California”, and assigns it to the state variable.
  • Inside the loop, the code prints the name of the state, which will initially be “California”.
  • Immediately after, the code appends this state’s name back to the states list.
  • As the loop continues, it finds another item in the states list, which is again “California” (since we added it during the first iteration).
  • This process keeps repeating endlessly, printing “California” over and over again and continually adding “California” to the list.

Output: This code will keep printing the message until you forcefully stop the Python program.

California
California
California
California
California
California
California
California
California
California
California
California
.
.
California
what is the difference between for loop and while loop in python

Python While Loop:

In Python, a while loop requires a condition to be specified. If we provide a value or an expression that always evaluates to True, then we’ll create an infinite loop, which will run indefinitely unless externally interrupted or broken using a break statement.

However, if we’re asking about the equivalent of a loop that runs indefinitely, we can use “while True:” which is a common pattern to create an infinite Python loop.

For instance, Imagine once we enter a diner, there’s a sign that says, “Free food every 5 minutes if you stay!” If we decide to stay in that diner based solely on that sign, we’ll never leave. Every 5 minutes, they serve us food, and there’s no end to it. That diner is like an infinite loop, continually serving food (or executing a command) with no stop in sight.

READ:  Python Check if a variable is a number

Let’s simulate a simple Python program that constantly sends a message like, “Enjoying food at the USA diner!”:

while True:  # This creates an infinite loop
    print("Enjoying food at the USA diner!")
    # A break statement or external interruption is needed to exit this loop.

Output: This Python code will keep printing the message until you forcefully stop the program.

Enjoying food at the USA diner!
Enjoying food at the USA diner!
Enjoying food at the USA diner!
Enjoying food at the USA diner!
Enjoying food at the USA diner!
Enjoying food at the USA diner!
Enjoying food at the USA diner!
Enjoying food at the USA diner!
Enjoying food at the USA diner!
Enjoying food at the USA diner!
Enjoying food at the USA diner!
Enjoying food at the USA diner!
.
.
Enjoying food at the USA diner!
difference between while loop and for loop in python

This no-condition situation in Python can be handled by using loop control statements.

Loop control statements in Python

In Python, loop control statements allow us to manage the execution flow within loops. These statements can change the loop’s regular behavior, either by skipping parts of the loop or by completely exiting it. There are three primary loop control statements: break, continue, and else:

BreakThe break statement is used to exit the current Python loop prematurely.
It breaks out of the smallest enclosing loop.
ContinueThe continue statement is used to skip the rest of the current iteration and move on to the next iteration of the Python loop.
ElseThe else clause in a loop is executed when the loop has finished iterating over the iterable (for “for loops”) or when the condition becomes False (for while loops) in Python.
The else block is not executed if the Python loop is terminated by a break statement.
Table for loop control statements in Python.

For loop vs while loop in Python

Let’s see the for and while loop differences in Python using tables: Where I will put the different basis for which the column has been decided and what are different conditions are for loop and in While loop for that.

Difference basis
for comparison
For loopWhile loop
Declarationfor variable in iterable:
# body of the loop
while condition:
# body of the loop
Basis of IterationIterates over a sequence or iterable objects in Python.Iterates as long as a condition remains True in Python.
InitializationInitialization is done at the time of Python loop definition (e.g., for state in states:)Initialization is usually done before the Python loop (e.g., money = 1000).
TerminationTerminates when all items in the Python sequence have been iterated over.Terminates when the specified condition becomes False in Python.
FlexibilityBest suited for scenarios where we know the number of iterations in advance or we are working with Python sequences.More flexible in scenarios where the number of iterations is unknown or dependent on dynamic conditions of Python.
Risk of Infinite LoopLess risk, as it works with a finite sequence in Python.Higher risk if the condition never becomes False in Python.
Modifying Loop Control VariableIt’s generally not recommended to modify the loop control variable.The loop control variable can be modified inside the loop without issues.
Difference between for loop and while loop in Python

Conclusion

This tutorial explains what a is For loop vs while loop in Python. This also explains what is for loop and what is a while loop is in Python with its syntax, examples, etc We have also explained the difference between a for loop and a while loop in Python using the table.

You may also like to read: