Difference Between For Loop and While Loop in Python

Learn via video course
FREE
View all courses
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Topics Covered

The loops are used to repeatedly execute the instructions till the condition is true. The difference between for loop and while loop is that for allows initialization, condition checking and iteration statements on the top of the loop, whereas while only allows initialization and condition checking at the top of the loop.

What are Loops?

Loops are the most powerful and basic concept in computer programming. A loop is an instruction that executes a statement until a specific condition is reached. The number of times the loop repeats itself is known as iteration. Some loop controlling statements are break and continue in Python. Various types of loops are for, while, do while, etc. Every programming language, including C, C++, Java, Python, etc., has the concept of a loop.

For Loop in Python

for loop is a control flow statement that executes code repeatedly for a particular number of iterations. In this control flow statement, the keyword used is for. The for loop is used when the number of iterations is already known, such as when iterating over lists, dictionaries, or strings, or when running a task a specific number of times with range().

Transform Your Career

Choose from our industry-leading programs designed for career success

NSDC Certified

Modern Software and AI Engineering Program

Master full-stack development with AI integration

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Modern Data Science and ML with specialisation in AI

Advanced data science techniques with AI specialization

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Advanced AIML with Specialisation in Agentic AI

Deep dive into AIML with focus on Agentic systems

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

DevOps, Cloud & AI Platform Engineering

Build and manage AI-powered cloud infrastructure

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

AI Engineering Advanced Certification by IIT-Roorkee

Premier AI engineering certification from IIT-Roorkee

3 MonthsDuration
AI-LedCurriculum
Career SupportSupport
Program highlights
Go to Program

The for loop has two parts:

  • Header: The header part specifies the iteration of the loop and controls it through an iterable rather than a boolean condition. In this part, the loop variable is also declared, which tells the body which iteration is executed.

  • Body: This part contains the statement executed per iteration within the loop’s block.

Let’s see the flow of the for loop:

  • Initialise the starting value

  • Check that the starting value is less than the stopping value.

  • Execute the statement.

  • Increment the starting value. Let’s see how the for loop works.

Flow of for Loops

**Syntax of for loop:**For-loop loop syntax is usually more concise than while-loop syntax because it does not need separate setup variables and manual updates.

Example of for loop:

Output

While Loop in Python

A loop that executes a single statement or a group of statements for the given true condition. The keyword used to represent this loop is while. A while loop is used when the number of iterations is unknown, such as when waiting for a network response or file completion based on a given condition. The statement repeats itself till the boolean value becomes false. Poor condition management can create an infinite loop. In a while loop, the condition is tested at the start, also known as the pre-test loop, and the code block runs only while that condition holds.

Let’s see the flow of the while loop:

  • Initialise the starting value

  • Check that the starting value is less than the stopping value.

  • Execute the statement.

  • Increment the starting value. Let’s see how the while loop works.

Flow for While Loops

Syntax of while loop:

Example of while loop:

Output:

Scaler Placement Report and Statistics

₹23L
AVG CTC
SCALER PLACEMENT PROOF

Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L.

11,000+placements
650+companies
Verified data

Difference Between For Loop and While Loop in Python

The major difference between For and While Loops in Python lies in how they control iteration and their usage: a For loop has a predictable number of steps, often iterating over elements using functions like “range” or directly over generators, while a While loop continues until a condition changes and allows for flexible initialization within its body. Performance-wise, For loops are generally faster than While loops.

Let’s see the difference between the for loop and the while loop:

ParameterFor LoopWhile Loop
KeywordFor Keyword is used.While Keyword is used.
UseNumber of iterations already known.No prior information on the number of iterations.
In absence of conditionLoop runs infinite times.Display the compile time error.
Initialization NatureOnce done cannot be repeated.Repeat at every iteration.
Initialization in accordance with iterationTo be done at starting of the loop.Can be done anywhere in the loop body.
Function usedRange or xrange function is used to iterate.No such function is used in the while loop.
Generator SupportFor loop can be iterated on generators in Python.While loop cannot be iterated on Generators directly.
EfficiencyMore efficient when iterating over sequences due to predetermined iterations.May be efficient in situations where the condition can be evaluated quickly.
Loop NatureUsed to iterate over a fixed sequence of items.Used for more dynamic scenarios where conditions dictate loop continuation.
SpeedFor loop is faster than while loop.While loop is slower as compared to for loop.

So these were the main difference between the for loop and the while loop.

Initialization of Loop Variable in Accordance to Iteration

In the case of the for loop, the syntax gets executed when the initialization is at the top of the syntax. On the other hand, in the case of the while loop, the position of the initialization statement does not matter for the syntax of the while loop to get executed.

Turn Learning into Career Growth

1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary
1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary

When to Use?

The for loop is used when we already know the number of iterations, which means when we know how many times a statement has to be executed. That is why we have to specify the ending point in the for loop initialization.

When execution must continue until a specific event or condition occurs rather than for a preset count, we use a while loop. This is the specific use case where a boolean expression controls repetition until the needed state is reached. A common example is a main game loop or validating user input until correct data is entered. The answer is that these loops serve different purposes, so the right choice depends on the situation.

Absence of Condition

When no condition is given in the for and while loop, both examples below show an infinite loop case. The difference between for loop and while loop in the absence of condition:

  • For loop: In the following example, the loop's code block repeats and will run infinite times.
  • While loop: The below loop will run infinite times.

Initialization Nature

In the case of a for loop, the initialization is done once at the start, so there is no need to initialize it again. But in the case of a while loop, we must manually define and update a variable, for example a count variable that changes on each iteration inside the loop body.

Learn More

Conclusion

Let’s conclude our topic, “difference between for loop and while loop,” by mentioning some of the important points. In short, use for loops for a known number of iterations or when traversing a collection such as an array, and use while loops when a boolean condition controls repetition.

  • In a for loop, the declarations, condition, and iteration expression are typically written together at the top, while the block of code inside the loop runs on each pass.

  • In a while loop, initialization is always outside the loop. The loop checks the condition each time, and the update can be performed before or after the execution of the statement(s).

  • A for loop is a control flow statement that executes code repeatedly for a particular number of iterations.

  • A while loop executes a single statement or a group of statements as long as the given condition is true; for example, you might print output on each iteration.

  • When no condition is given in the for loop, the loop will iterate infinite times, while in the case of the while loop, it will give an error (compile time error).

Hiring Partners:
GoogleGoogleAmazonAmazonMicrosoftMicrosoftFlipkartFlipkartAdobeAdobe1200+ more