Difference between For Loop and While Loop in Python
Basics of SQL
12 Hrs. duration
12 Modules
2600+ Learners
Start Learning
Loops are an important part of programming that helps in executing a block of code repeatedly. In Python, the two most common loops are the For loop and the While loop. Both these loops help in iteration but work differently and have different use cases. Understanding these differences can do magic to your programming approach and efficiency. In this article, we will compare For Loop and While Loop differences in Python. Before we get a deep dive into the difference, let us first understand the basic concept of loops.
Loops are the most basic things in programming. A loop is a programming technique that repeats a block of code or set of instructions over and over again without explicitly writing it out. This piece of code is executed based on a certain condition. Loops constitute the control structures of a program.
Loops are one of the core concepts in programming and are used often in making programs. Every programming language has loops as a fundamental concept; be it C++, Java, Python, and many others. There are different types of loops in every other programming language like For loop, While loop, do-while, etc. In Python, there are only two types of loops: The for loop and the While loop; let’s discuss them one by one in detail.
For Loop in Python
A For loop is used to iterate over a sequence of items in Python, such as a tuple, list, string, or range. For each element in the sequence, the loop runs a specific block of code.
Syntax:
sequence = [True, True] # Initialization
for variable in sequence: # condition and updation
statements(s) # Code block statements
How Does a For Loop Work?
Step 1: Initialisation
The for loop starts with setting the loop variable to the first element of the iterated object (list, range) and then begins traversing it.
For example, if a loop is iterating over a sequence, i.e., range(5), it assigns the first value of the range to that variable.
Step 2: Condition Check
In a for loop the condition is implicit. Unlike in a while loop where you explicitly define a condition that stops it, the for loop goes on to execute until all elements in the sequence are covered.
Python internally checks if there are more elements in the sequence.
Step 3: Loop body execution
The loop body is run; it contains the code to be executed on each iteration. This may include carrying out operations like print, adjusting variables, and compute.
Step 4: After executing the loop body, Python moves to the next element in the sequence. The next value in the iterable automatically updates the loop variable.
Step 5: Repeat steps 2 to 4, for each element in the sequence.
Step 6: Once the sequence has been completely iterated over (no more elements are left), the loop exits, and the control moves to the first statement after the for loop.
It loops through a sequence (such as a range, list, or string).
The length of the sequence shows how many iterations there will be.
Improved and more concise syntax while utilising sequences.
Frequently used when the total number of iterations is predetermined.
Example:
# define a list
prog_lang = ["Java", "Python", "C++"]
# run a for loop
for lang in prog_lang:
print(lang) # print programming languages
Output:
Java
Python
C++
While Loop in Python
The while loop continues to execute a block of code as long as a given condition is true. The condition is checked before every iteration, and the loop stops when the condition becomes false.
Syntax:
expression = True # Initialization
while expression: # While loop condition
statement(s) # Code block
How Does a While Loop Work?
Step 1: Initialisation
Before entering the while loop, the loop controlling condition must be initialised. This typically means setting up a variable that is going to control the condition (e.g., a counter).
Step 2: Condition Check
It tests the condition at the beginning of each iteration. If True, it executes the body; if False, it ends.
Step 3: Execution of Loop Body
If the condition is true, the code inside the loop body runs. This means performing calculations, printing values, or changing variable values.
Step 4: Updation of Condition
At this step, those variables in the loop that control the condition (like a counter) are updated. If this is not done and the condition is never updated elsewhere, then if need be the loop would go on endlessly (an infinite loop).
Step 5: Repeat steps 2 to 4, after the loop body executes, check the condition. If the condition is true, repeat the loop.
Step 6: The while loop ends and control shifts to the first statement after the loop when the condition is no longer true.
Characteristics of While Loop
It is a loop with conditions.
Useful when it’s unclear how many iterations there will be.
Every time an iteration begins, the condition is verified.
It may result in never-ending cycles if the condition is never broken.
Example:
password = "" # initially password is empty
while password != "hello": # run a while loop
password = input("Enter correct password: ") # get user input
print("You're granted access!") # prints the output
Output:
Enter the correct password: h
Enter the correct password: hello
Below are the key differences between the For loop and the While loop in Python:
Criteria
For Loop
While Loop
Usage
Used when the number of iterations is known beforehand.
Used when the number of iterations is not known, and the loop depends on a condition.
Syntax
for variable_name in sequence:
while condition:
Control
For loop iterates over a sequence and the number of iterations is determined by the length of the sequence.
While loop runs as long as the condition is true, and can result in an infinite loop if the condition never becomes false.
Termination
Terminates after iterating through the entire sequence.
Terminates when the condition becomes false.
Performance
It is faster due to internal improvements when repeating a sequence.
It may be slow if the condition is complicated and requires more time to assess.
Speed
It is faster as compared to the while loop.
It is slower compared to a for loop.
Nature
A for loop has a basic nature in Python.
While loops have a complex nature in Python.
Function used
In Python, range or xrange are common functions used.
In Python, there are no specific functions used for while loops.
Efficiency
It is more efficient to iterate over sequences as the iterations are predetermined.
When the condition can be rapidly assessed, it might be effective.
Use case
Iterating through ranges, tuples, lists, or strings.
Used where you must continuously verify a condition such as waiting for user input.
Infinite Loop in Python
An infinite loop is characterised by the absence of a working exit strategy. As a result, the loop keeps repeating until the operating system detects it and ends the program with an error or until another event happens (such as setting an automatic program termination after a predetermined amount of time).
Infinite For Loop
In a For loop, an infinite loop is impossible but may occur if it is used with generators or iterators. See the below example.
Example:
from itertools import count
for i in count(0):
print(i)
In this example, count(0) creates an infinite series of numbers beginning at 0, which keeps the loop running forever.
Infinite While Loop
The infinite loop problem is more common in a While loop. See the below example.
Example:
while True:
print("Infinite loop message!")
In this example, the condition True is always true, therefore this loop will continue forever. Either manually interrupt the loop or use a break statement to end it.
When to Use For Loops
A For loop must be used at the correct time according to the program requirements. Here’s when to use the For loops in Python:
Iterating through a sequence: Lists, tuples, or strings are the perfect objects to iterate over using the for loop. For example, Processing characters in a string or iterating through a list of items.
Working with ranges: When processing a fixed range of integers, for example, or when you need to iterate a certain amount of times, use for loops.
More straightforward and readable: The For loops are typically simpler to read and comprehend, particularly when dealing with sequences that have a definite number of iterations.
When to Use While Loops
A While loop must be used at the correct time according to the program requirements. Here’s when to use a while loop in Python:
Condition-based loops: The while loop works better when the loop’s termination is dependent on a dynamic condition. For example, keep requesting input from the user until the right response is given.
Unknown number of iterations: A while loop is a better option if you’re not sure how many times the loop will execute.
Managing complex conditions: The while loop offers flexibility if you need to run the loop depending on a condition involving several variables or outside variables.
Best Practices for Both For and While Loops
1.Avoid Unnecessary Computation
If loops execute pointless calculations throughout each iteration, they may be inefficient. For example, calculating the same value repeatedly within the loop can cause it to execute more slowly.
2.Using Break when required
Try using the break statement to end a loop early if you know that its task is finished before all of its iterations are completed. By reducing pointless iterations, performance can be enhanced in this way.
3. Use enumerate()
To make the code more readable and Pythonic, use Python’s enumerate() method rather than a counter when you need both the index and the value in a for loop.
Conclusion
Python has two fundamental loop constructs: while and for loops. Knowing the difference between the two will help you develop more effective code. The while loop performs better in scenarios where the number of iterations is dependent on a dynamic condition, whereas the for loop is better suited for looping over sequences where the number of iterations is known.
FAQs
What is the syntax of for loop in Python?
The syntax of for loop in Python is very simple. The syntax is as follows:
Syntax:
for variable_name sequence:
# body
Which is better a while loop or a for loop?
Both while and for loops have different ways of working and can be helpful when applied appropriately. We use a while loop when the iterations are unknown, and a for loop when the iterations are known.
How to use While True in Python?
The while True loop runs indefinitely until a break statement is encountered. It’s useful for situations requiring continuous execution, such as waiting for input or events, but must include a condition to exit to prevent infinite loops. For example:
while True:
# loop until break
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.