Difference between For Loop and While Loop in Python

Difference between For Loop and While Loop in Python

15 Apr 2024
Beginner
13.9K Views
9 min read
Learn with an interactive course and practical hands-on labs

Free Data Structures & Algorithms Online Course

Difference Between for loop and while loop in Python: An Overview

Difference between For and While loops is easy to understand if you know their usage and applicationin aPython program. In this Python Tutorial, we will try to understand topics likeWhat is Python for loop?,What is Python while loop?, and the major differences between for loop and while loop in Python. You can explore more about different other concepts of python programming by enrolling in our Python Certification Training.

Read More: Top 50 Python Interview Questions and Answers

What is Python for loop?

A for loop in Python is used for repetition of a specified sequence of elements. It maybe a list, a tuple, a set, a dictionary or even a string.

Flowchart of Python for loop:

Python for loop flowchart

Python for loop Syntax

The for loop syntax in Python looks like this:
for item in iterable:
    # Code block
  • The variable 'item' will take each value from the specified sequence..
  • The code block under the for loop will execute for each value.

Example of Python for loop

Here is an example of for loop in Python Editor:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

Explanation:

The variable 'fruits' is assigned with certain elements. These elements will be taken one by one to execute the block of code in the for loop for the values of each of the elements.

Output

apple
banana
cherry

What is Python while loop?

Python while loop is the control flow statement that repeats a block of code till the time a specified condition is 'True'. It keeps the iteration going until the condition is 'True' and as soon as the condition is 'False', the while loop in Python is terminated and the next line of code is executed which is just ahead of it.

Flowchart of Python while loop:

python while loop flowchart

Python while loop Syntax

The while loop syntax in Python looks like this:

while condition:
    # Code block
  • The while loop will evaluate the condition and execute the code block if it is 'True'.
  • Once the condition becomes 'False', the loop will terminate itself.

Read More: Python Developer Salary

Example of Python while loop

To understand the python while loop better, have a look at this simple example of while loop in Python Compiler, that will count the numbers from 1 to 5 and print it:
# Initialize a variable to store the current number
number = 1

# Start the while loop
while number <= 5:
    # Print the current number
    print(number)
    
    # Increment the number for the next iteration
    number += 1

Explanation:

Here, in the above example, we have first initialized a variable 'number' as '1' then we have given it a condition with while loop that the 'number' needs to be less than or equal to 5. The 'number' is iterated with an increment of 1 each time. The loop will get terminated as soon as the number becomes 6 which will evaluate to 'False' as 6 is neither less than nor equal to 5. The output will be as shown below:

Output

1
2
3
4
5

Difference Between For Loop and While Loop in Python

Here is a comparison table differentiating for loop and while loop:
AspectFor LoopWhile Loop
Syntaxfor item in iterable:while condition:
Iteration behaviorIt iterates through the specified sequence by itself.It depends on the condition, whether it is 'True' or 'False'.
Number of iterationsThe number of iterations is known or finite.The number of iterations is not known.
ExecutionExecution depends on the specific number of iterations.It repeats the execution based on the specified condition.
TerminationIt will terminate once all elements have gone through iteration.It may result in an infinite loop if the condition never evaluates to 'False'.
EfficiencyIt is considered more efficient.It is less efficient as compared to the other.
Error PotentialIt iterates through a sequence, hence, less prone to infinite loops.It may lead to frequent infinite loops if conditions are not managed carefully.

When to use For Loop and While Loop in Python?

To decide when should you use for loop and when to use while loop, you can think of these situations and you will the answer:

For Loop

  • When there is a need of iteration over elements that are in sequence like lists, tuples, strings or dictionaries.
  • Use for loops when a known number or a finite number of iteration is required.
  • Another situation when you want that each element of a sequence should pass through iteration one by one.
  • for loops can also be used when a task requires a sequential access of elements of a sequence.

While Loop

  • When there is a need to repeat execution of a block of code until a specified condition becomes False.
  • Use while loops when the number of iteration is not determined.
  • while loops are can be used when there is a need to repeat execution based on a condition.
  • When dynamic adaptation is required based upon condition that may change.

What happens in the Absence of Condition

In Python, both for loop and while loop work with a condition involved that determines when the loop will stop. If there is no condition involved within both of these loops, the execution will change accordingly.

For Loop

If the condition in the for loop is omitted, it will no length or range for determining the iteration. So, without a condition a for loop will not perform execution of any iteration, which means there will be no output.
# This for loop won't execute any iterations since there's no iterable to iterate over
for i in range():  # range() without arguments doesn't generate any values
    print("This loop won't execute any iterations!")

Output

(no output)

While Loop

Similarly, if the condition in the while loop is omitted, it will also show certain changes in the execution. Without a condition, a while loop will lead to an infinite loop, which means it will continue to execute the code block under while loop infinitely.
# This while loop will run infinitely since there's no condition to stop it
while True:
    print("This loop will run forever!")

Output

This loop will run forever!
This loop will run forever!
This loop will run forever!
...
Summary
This article explains what is the major difference between for loop and while loop in Python and how do they differ in various applications and conditions. If you want to know more about different concepts of Python Programming, consider enrolling in our Python Certification Course right now and get your hands on the best comprehensive guide to Python core concepts.

FAQs

A for loop in Python repeats executing a code block from a sequence till certain number of times. Whereas a while loop in Python repeats execution of a code block till the condition is true which is not certain.

The while loop is used in Python when a block of code needs to be executed on repeat till a specified condition is true. 

The for loop in Python is used when there is a need to iterate over a sequence until all elements are done.

The syntax of while loop:
while condition:
    # Code block to execute while condition is True

Both while and for loops in Python are equal in terms of iteration. They can be decided on the basis of their use cases.
Share Article
About Author
Sakshi Dhameja (Author and Mentor)

She is passionate about different technologies like JavaScript, React, HTML, CSS, Node.js etc. and likes to share knowledge with the developer community. She holds strong learning skills in keeping herself updated with the changing technologies in her area as well as other technologies like Core Java, Python and Cloud.

Accept cookies & close this